forked from fanfank/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-tree-preorder-traversal.cpp
More file actions
38 lines (38 loc) · 1019 Bytes
/
binary-tree-preorder-traversal.cpp
File metadata and controls
38 lines (38 loc) · 1019 Bytes
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
/**
* 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;
}
};