-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_tree_postorder_traversal.cpp
More file actions
78 lines (69 loc) · 1.32 KB
/
Copy pathbinary_tree_postorder_traversal.cpp
File metadata and controls
78 lines (69 loc) · 1.32 KB
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
#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:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
if(nullptr == root)
{
return result;
}
stack<TreeNode*> tree_stack;
TreeNode* cur = nullptr;
TreeNode* pre = nullptr;
tree_stack.push(root);
while(!tree_stack.empty())
{
cur = tree_stack.top();
if((nullptr == cur->left && nullptr == cur->right) ||
(nullptr != pre && (pre == cur->left || pre == cur->right)))
{
tree_stack.pop();
result.push_back(cur->val);
pre = cur;
}
else
{
if(nullptr != cur->right)
{
tree_stack.push(cur->right);
}
if(nullptr != cur->left)
{
tree_stack.push(cur->left);
}
}
}
return result;
}
};
int main(void)
{
TreeNode t1 = {1};
TreeNode t2 = {2};
TreeNode t3 = {3};
TreeNode t4 = {4};
TreeNode t5 = {5};
t1.left = &t2;
t1.right = &t3;
t2.left = &t4;
t2.right = &t5;
Solution solution;
vector<int> result = solution.postorderTraversal(&t1);
for(auto& data : result)
{
cout << data << " " << endl;
}
return 0;
}