-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary_Tree_Postorder_Traversal.cpp
More file actions
41 lines (38 loc) · 1.02 KB
/
Binary_Tree_Postorder_Traversal.cpp
File metadata and controls
41 lines (38 loc) · 1.02 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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//O(N)
//O(N)
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> result;
if(!root) return result;
stack<TreeNode *> stk;
while(!stk.empty()||root)
{
while(root)
{
stk.push(root);
root=root->left;
}
if(!stk.empty()&&stk.top()->right&&(result.empty()||result.back()!=stk.top()->right->val))
{
root=stk.top()->right;
}
else
{
result.push_back(stk.top()->val);
stk.pop();
root=NULL;
}
}
return result;
}
};