/
binary-tree-postorder-traversal.cpp
95 lines (75 loc) · 1.84 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
86
87
88
89
90
91
92
93
94
95
#include <vector>
#include <stack>
#include <iostream>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct record
{
struct TreeNode *p;
int flag;
};
class Solution
{
public:
vector<int> postorderTraversal(TreeNode *root)
{
stack<struct record> s;
vector<int> result;
if (!root) {
return result;
}
struct record first;
first.p = root;
first.flag = 0;
s.push(first);
while (!s.empty()) {
struct record &frame = s.top();
frame.flag++;
if (1 == frame.flag) {
// left child
if (frame.p->left) {
struct record temp;
temp.p = frame.p->left;
temp.flag = 0;
s.push(temp);
}
continue;
}
if (2 == frame.flag) {
// right child
if (frame.p->right) {
struct record temp;
temp.p = frame.p->right;
temp.flag = 0;
s.push(temp);
}
continue;
}
if (3 == frame.flag) {
// root
result.push_back(frame.p->val);
s.pop();
continue;
}
}
return result;
}
};
int main(int argc, char *argv[])
{
TreeNode node1(1), node2(2), node3(3);
node1.right = &node2;
node2.left = &node3;
Solution solution;
vector<int> result = solution.postorderTraversal(&node1);
for (vector<int>::iterator iter = result.begin(); iter != result.end(); iter++) {
cout << *iter << endl;
}
return 0;
}