-
Notifications
You must be signed in to change notification settings - Fork 2
/
145. Binary Tree Postorder Traversal.cpp
71 lines (66 loc) · 1.64 KB
/
145. 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
class Solution1 {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int>res;
stack<TreeNode*>stk;
if (root==NULL){
return res;
}
TreeNode* last=NULL;
while (root!=NULL||!stk.empty()){
if (root!=NULL){
stk.push(root);
root=root->left;
}else{
TreeNode* n=stk.top();
if (n->right==NULL||last==n->right){
res.push_back(n->val);//如果为空,访问根节点,如刚刚访问右节点,访问根节点。
stk.pop();
last=n;
}else{
root=n->right;
}
}
}
return res;
}
};
class Solution2 {
public:
vector<int> postorderTraversal2(TreeNode *root) {
vector<int> result;
postorderHelper(root, result);
return result;
}
void postorderHelper(TreeNode *root, vector<int> &result) {
if (root == NULL) return;
postorderHelper(root->left, result);
postorderHelper(root->right, result);
result.push_back(root->val);
}
};
class Solution3 {
public:
vector<int>res;
vector<int> postorderTraversal(TreeNode* root) {
if (root == NULL)
return res;
stack<TreeNode*>stk;
while (root||!stk.empty()){
if (root) {
stk.push(root);
res.insert(res.begin(), root->val);
root = root->right;
}
else {
root = stk.top();
stk.pop();
root = root->left;
}
}
return res;
}
};
//还是不太好啊,pretty good
// n,last 那边总是出错啊,root=n1->right
// 还是在n那边容易出错啊,加油, 只是三种方法都不会了,今天再做一遍