-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Tree Postorder Traversal.cpp
85 lines (81 loc) · 1.66 KB
/
Binary Tree Postorder 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
78
79
80
81
82
83
84
85
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
/**
* Definition for a binary tree node.
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
/*
Recursive
void solve(TreeNode* root, vector<int> &res) {
if(!root) {
return;
}
solve(root->left, res);
res.push_back(root->val);
solve(root->right, res);
}
*/
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) {
return res;
}
stack<TreeNode *> s;
TreeNode *cur, *pre = NULL;
s.push(root);
while(!s.empty()) {
cur = s.top();
bool noChild = false;
if(!cur->left && !cur->right) {
noChild = true;
}
bool childVisited = false;
if(pre && (cur->left == pre || cur->right == pre)) {
childVisited = true;
}
if(noChild || childVisited) {
res.push_back(cur->val);
s.pop();
pre = cur;
}
else {
if(cur->right) {
s.push(cur->right);
}
if(cur->left) {
s.push(cur->left);
}
}
}
return res;
}
};
TreeNode *buildTree(int depth, int &val) {
TreeNode *root = new TreeNode(val);
if(depth == 0) {
return root;
}
root->left = buildTree(depth - 1, ++val);
root->right = buildTree(depth - 1, ++val);
return root;
}
int main() {
int val = 1;
TreeNode *tree = buildTree(2, val);
Solution s;
std::vector<int> res;
res = s.postorderTraversal(tree);
for(int i = 0; i < res.size(); i++) {
cout << res[i] << endl;
}
return 0;
}