forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreePostorderTraversal.cpp
More file actions
37 lines (36 loc) · 913 Bytes
/
BinaryTreePostorderTraversal.cpp
File metadata and controls
37 lines (36 loc) · 913 Bytes
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
/**
* Definition for binary tree
* 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> res;
if(!root) {
return res;
}
stack<TreeNode* > s;
s.push(root);
TreeNode* child = root;
while(!s.empty()) {
TreeNode* top = s.top();
if( (!top->left&&!top->right) || top->left == child || top->right == child) {
res.push_back(top->val);
child = top;
s.pop();
continue;
}
if(top->right)
s.push(top->right);
if(top->left)
s.push(top->left);
child=top;
}
return res;
}
};