forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main9.cpp
89 lines (70 loc) · 1.92 KB
/
main9.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
/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/
/// Author : liuyubobobo
/// Time : 2018-05-31
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
/// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// Morris PostOrder Traversal
//
// Time Complexity: O(n)
// Space Complexity: O(1)
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if(root == NULL)
return res;
TreeNode* dummyRoot = new TreeNode(-1);
dummyRoot->left = root;
TreeNode* cur = dummyRoot;
while(cur != NULL){
if(cur->left == NULL)
cur = cur->right;
else{
TreeNode* prev = cur->left;
while(prev->right != NULL && prev->right != cur)
prev = prev->right;
if(prev->right == NULL){
prev->right = cur;
cur = cur->left;
}
else{
prev->right = NULL;
reverseTraversal(cur->left, res);
cur = cur->right;
}
}
}
delete dummyRoot;
return res;
}
private:
void reverseTraversal(TreeNode* node, vector<int>& res){
int start = res.size();
while(node != NULL){
res.push_back(node->val);
node = node->right;
}
reverse(res.begin() + start, res.end());
}
};
void print_vec(const vector<int>& vec){
for(int e: vec)
cout << e << " ";
cout << endl;
}
int main() {
TreeNode* root = new TreeNode(1);
root->right = new TreeNode(2);
root->right->left = new TreeNode(3);
print_vec(Solution().postorderTraversal(root));
return 0;
}