forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary-tree-postorder-traversal.cpp
112 lines (107 loc) · 3.34 KB
/
binary-tree-postorder-traversal.cpp
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Time: O(n)
// Space: O(1)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
// Morris Traversal.
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> res;
TreeNode dummy(INT_MIN);
dummy.left = root;
TreeNode *curr = &dummy;
while (curr) {
if (!curr->left) {
curr = curr->right;
} else {
TreeNode *node = curr->left;
while (node->right && node->right != curr) {
node = node->right;
}
if (!node->right) {
node->right = curr;
curr = curr->left;
} else {
vector<int> v = trace_back(curr->left, node);
res.insert(res.end(), v.begin(), v.end());
node->right = nullptr;
curr = curr->right;
}
}
}
return res;
}
vector<int> trace_back(TreeNode *frm, TreeNode *to) {
vector<int> res;
TreeNode *curr = frm;
while (curr != to) {
res.emplace_back(curr->val);
curr = curr->right;
}
res.emplace_back(to->val);
reverse(res.begin(), res.end());
return res;
}
};
// Time: O(n)
// Space: O(h)
// Stack solution.
class Solution2 {
/**
* @param root: The root of binary tree.
* @return: Postorder in vector which contains node values.
*/
public:
vector<int> postorderTraversal(TreeNode *root) {
if (root == nullptr) { // Empty tree.
return {};
}
stack<TreeNode *> path_stack;
TreeNode * prev = nullptr;
path_stack.emplace(root);
vector<int> postorder_sequence;
while (!path_stack.empty()) {
auto curr = path_stack.top();
if (prev == nullptr || prev->left == curr ||
prev->right == curr) {
// We came down to curr from prev.
if (curr->left != nullptr) { // Traverse left.
path_stack.emplace(curr->left);
} else if (curr->right != nullptr) { // Traverse right.
path_stack.emplace(curr->right);
} else { // Leaf node, so visit current node.
postorder_sequence.emplace_back(curr->val);
path_stack.pop();
}
} else if (curr->left == prev) {
// Done with left, so now traverse right.
if (curr->right != nullptr) {
path_stack.emplace(curr->right);
} else { // No right child, so visit curr.
postorder_sequence.emplace_back(curr->val);
path_stack.pop();
}
} else {
// Finished traversing left and right, so visit curr.
postorder_sequence.emplace_back(curr->val);
path_stack.pop();
}
prev = curr;
}
return postorder_sequence;
}
};