-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBinary Tree Postorder Traversal.cpp
55 lines (50 loc) · 1.11 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
#include <iostream>
#include <vector>
#include <set>
#include <stack>
#include <vector.h>
using namespace std;
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){
set<TreeNode*> visited;
stack<TreeNode*> s;
vector<int> result;
if(root==NULL) return result;
TreeNode* temp;
while(root || !s.empty()){
if(root){
s.push(root);
root = root->left;
}
else{
if(!s.empty()){
temp = s.top();s.pop();
if(temp->right && visited.find(temp->right)==visited.end()){
s.push(temp);
visited.insert(temp->right);
root = temp->right;
}
else{
result.push_back(temp->val);
}
}
}
}
return result;
}
};
int main(){
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
Solution s;
Vector<int> v = Vector<int>(s.postorderTraversal(root));
cout << v.toString();
}