-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary Tree Postorder Traversal.cpp
77 lines (71 loc) · 1.96 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
/*
Given a binary tree, return the postorder traversal of its nodes' values.
Link: http://www.lintcode.com/en/problem/binary-tree-postorder-traversal/
Example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Solution: None
Source: https://github.com/kamyu104/LintCode/blob/master/C%2B%2B/binary-tree-postorder-traversal.cpp
*/
/**
* 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) {
// write your code here
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;
}
};