forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-tree-postorder-traversal_2(AC).cpp
More file actions
48 lines (48 loc) · 1.2 KB
/
binary-tree-postorder-traversal_2(AC).cpp
File metadata and controls
48 lines (48 loc) · 1.2 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
42
43
44
45
46
47
48
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
* @param root: The root of binary tree.
* @return: Postorder in vector which contains node values.
*/
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> ans;
if (root == NULL) {
return ans;
}
vector<TreeNode *> st;
TreeNode *p = root, *oldp;
while (true) {
while (p != NULL) {
st.push_back(p);
p = p->left;
}
while (!st.empty() && st.back()->right == NULL) {
ans.push_back(st.back()->val);
oldp = st.back();
st.pop_back();
}
while (!st.empty() && oldp == st.back()->right) {
ans.push_back(st.back()->val);
oldp = st.back();
st.pop_back();
}
if (st.empty()) {
break;
}
p = st.back()->right;
}
return ans;
}
};