-
Notifications
You must be signed in to change notification settings - Fork 0
/
144_Binary-Tree-Preorder-Traversal.cpp
61 lines (54 loc) · 1.47 KB
/
144_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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
//Solution: Recursion
/*
void dfs_bottom(TreeNode* node, vector<int>* vi) {
if(!node) return;
dfs_bottom(node->left, vi);
dfs_bottom(node->right, vi);
vi->push_back(node->val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int>vi;
if(!root) return vi;
dfs_bottom(root->left, &vi);
dfs_bottom(root->right, &vi);
vi.push_back(root->val);
return vi;
}
*/
//Solution: Two Stacks
vector<int> postorderTraversal(TreeNode* root) {
vector<int>vi;
if(!root) return vi;
stack<TreeNode*> s1, s2;
s1.push(root);
while(!s1.empty()){
TreeNode *cur = s1.top();
s1.pop();
s2.push(cur);
if(cur->left != nullptr){
s1.push(cur->left);
}
if(cur->right != nullptr){
s1.push(cur->right);
}
}
while(!s2.empty()){
vi.push_back(s2.top()->val);
s2.pop();
}
return vi;
}
};