forked from iphkwan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary_Tree_Preorder_Traversal.cc
37 lines (37 loc) · 1.05 KB
/
Binary_Tree_Preorder_Traversal.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<int> ret;
TreeNode *cur = root, *tmp = NULL;
while (cur) {
if (!cur->left) {
ret.push_back(cur->val);
cur = cur->right;
} else {
tmp = cur->left;
while (tmp->right && tmp->right != cur)
tmp = tmp->right;
if (!tmp->right) {
tmp->right = cur;
ret.push_back(cur->val);
cur = cur->left;
} else {
tmp->right = NULL;
cur = cur->right;
}
}
}
return ret;
}
};