-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostorder_traversal.cpp
More file actions
35 lines (35 loc) · 841 Bytes
/
Copy pathPostorder_traversal.cpp
File metadata and controls
35 lines (35 loc) · 841 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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
vector<int> Solution::postorderTraversal(TreeNode* A) {
vector<int> res;
if(!A)
return res;
stack<TreeNode*> postorder;
do{
while(A){
if(A->right)
postorder.push(A->right);
postorder.push(A);
A = A->left;
}
A = postorder.top();
postorder.pop();
if(A->right && !postorder.empty() && postorder.top()==A->right){
postorder.pop();
postorder.push(A);
A = A->right;
}
else{
res.push_back(A->val);
A = NULL;
}
}while(!postorder.empty());
return res;
}