forked from iphkwan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary_Tree_Postorder_Traversal.cc
53 lines (51 loc) · 1.58 KB
/
Binary_Tree_Postorder_Traversal.cc
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
/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
TreeNode *dump = new TreeNode(0);
dump->left = root;
vector<int> ret;
int L, R;
TreeNode *cur = dump, *tmp = NULL, *helper = NULL;
while (cur) {
if (!cur->left) {
cur = cur->right;
} else {
tmp = cur->left;
while (tmp->right != NULL && tmp->right != cur)
tmp = tmp->right;
if (tmp->right != cur) {
tmp->right = cur;
cur = cur->left;
} else {
//print
L = ret.size();
helper = cur->left;
while (helper != cur) {
ret.push_back(helper->val);
helper = helper->right;
}
R = ret.size() - 1;
//reverse
while (L < R) {
swap(ret[L++], ret[R--]);
}
tmp->right = NULL;
cur = cur->right;
}
}
}
delete dump;
return ret;
}
};