Skip to content

Commit daad649

Browse files
committed
2
1 parent 6e258a5 commit daad649

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* Definition for binary tree
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
void print(vector<int>& result, TreeNode* from, TreeNode* to) {
13+
vector<int> temp;
14+
while (true) {
15+
temp.push_back(from->val);
16+
if (from == to) {
17+
break;
18+
}
19+
from = from->right;
20+
}
21+
for (int i = temp.size() - 1; i >= 0; i--) {
22+
result.push_back(temp[i]);
23+
}
24+
}
25+
26+
vector<int> postorderTraversal(TreeNode *root) {
27+
vector<int> result;
28+
TreeNode prev(0);
29+
prev.left = root;
30+
TreeNode* curr = &prev;
31+
while (curr != NULL) {
32+
if (curr->left == NULL) {
33+
curr = curr->right;
34+
} else {
35+
TreeNode* next = curr->left;
36+
while (next->right && next->right != curr) {
37+
next = next->right;
38+
}
39+
if (next->right == NULL) {
40+
next->right = curr;
41+
curr = curr->left;
42+
} else {
43+
print(result, curr->left, next);
44+
next->right = NULL;
45+
curr = curr->right;
46+
}
47+
}
48+
}
49+
return result;
50+
}
51+
};

0 commit comments

Comments
 (0)