-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Tree Postorder Traversal.cpp
92 lines (78 loc) · 1.8 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
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
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) {
// result = new std::vector<int>;
// trav(root);
// return *result;
result = new std::vector<int>;
if(root==NULL) return *result;
iter(root);
return *result;
}
void iter(TreeNode *root)
{
stack<pair<TreeNode *, bool> > nodes;
nodes.push(make_pair(root, false));
while(!nodes.empty())
{
pair<TreeNode*, bool> *node = &nodes.top();
if(node->second)
{
result->push_back(node->first->val);
nodes.pop();
}
else
{
node->second = true;
if(node->first->right!=NULL)
nodes.push(make_pair(node->first->right, false));
if(node->first->left!=NULL)
nodes.push(make_pair(node->first->left, false));
}
}
}
void trav(TreeNode *node)
{
if(node==NULL) return;
trav(node->left);
trav(node->right);
result->push_back(node->val);
}
private:
std::vector<int> *result;
};
int main()
{
TreeNode *root = new TreeNode(3);
root->left = new TreeNode(9);
root->right = new TreeNode(20);
root->right->left = new TreeNode(15);
root->right->right = new TreeNode(7);
Solution s;
std::vector<int> v = s.postorderTraversal(root);
for(int i=0; i<v.size(); i++)
{
cout << v[i] << " ";
}
cout << endl;
return 0;
}