-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Tree Preorder Traversal.cpp
56 lines (48 loc) · 1.44 KB
/
Binary Tree Preorder Traversal.cpp
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void do_traverse(vector<int> &record, TreeNode *root) {
if (root == nullptr)
return;
record.push_back(root->val);
do_traverse(record, root->left);
do_traverse(record, root->right);
}
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> result ;
do_traverse(result, root);
return result;
}
};
// Non-recursive by using stack
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<TreeNode *> stk;
vector<int> record;
TreeNode *cur;
stk.push_back(root);
while (!stk.empty()) {
cur = stk.back();
stk.pop_back();
if (cur == nullptr)
continue;
record.push_back(cur->val);
stk.push_back(cur->right);
stk.push_back(cur->left);
}
return record;
}
};