forked from MaskRay/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary-tree-postorder-traversal.cc
65 lines (63 loc) · 1.37 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
54
55
56
57
58
59
60
61
62
63
64
65
// Binary Tree Postorder Traversal
// stack
class Solution {
public:
vector<int> postorderTraversal(TreeNode *p) {
vector<int> a;
stack<TreeNode *> s;
for(;;) {
while (p) {
s.push(p);
p = p->left;
}
while (! s.empty() && s.top()->right == p) {
p = s.top();
s.pop();
a.push_back(p->val);
}
if (s.empty()) break;
p = s.top()->right;
}
return a;
}
};
// Morris post-order traversal
class Solution {
void reverse_right_chain(TreeNode *x, TreeNode *y) {
TreeNode *p = x, *q = x->right, *right;
while (p != y) {
right = q->right;
q->right = p;
p = q;
q = right;
}
}
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> ret;
TreeNode aux(0), *p = &aux;
aux.left = root;
aux.right = NULL;
while (p) {
TreeNode *q = p->left;
if (q) {
while (q->right && q->right != p) q = q->right;
if (q->right == p) {
reverse_right_chain(p->left, q);
for (TreeNode *r = q; ; r = r->right) {
ret.push_back(r->val);
if (r == p->left) break;
}
reverse_right_chain(q, p->left);
q->right = NULL;
} else {
q->right = p;
p = p->left;
continue;
}
}
p = p->right;
}
return ret;
}
};