-
Notifications
You must be signed in to change notification settings - Fork 95
/
binary-tree-preorder-traversal.cpp
77 lines (75 loc) · 1.91 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/****************************************
* solution 1: a complicate solution
****************************************/
/**
* 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> v;
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.
v.clear();
queue<TreeNode*> q;
stack<TreeNode*> s;
if(root)
q.push(root);
while(!q.empty() || !s.empty()) {
while(!q.empty()) {
TreeNode *tmp = q.front();
q.pop();
v.push_back(tmp->val);
if(tmp->left)
q.push(tmp->left);
s.push(tmp);
}
if(!s.empty()) {
if(s.top()->right)
q.push(s.top()->right);
s.pop();
}
}
return v;
}
};
/****************************************
* solution 2: a simpler solution
****************************************/
/**
* 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) {
vector<int> v;
stack<TreeNode*> s;
if (root) {
s.push(root);
}
while (!s.empty()) {
TreeNode *node = s.top();
s.pop();
v.push_back(node->val);
if (node->right) {
s.push(node->right);
}
if (node->left) {
s.push(node->left);
}
}
return v;
}
};