-
Notifications
You must be signed in to change notification settings - Fork 0
/
pre_in_post.cpp
72 lines (69 loc) · 1.77 KB
/
pre_in_post.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
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*>q;
vector<int> ans;
TreeNode* now=root;
while(now||!q.empty()){
while(now){
ans.push_back(now->val);
q.emplace(now);
now=now->left;
}
//每次从栈中出现的值,我都取它的右结点
TreeNode* temp=q.top();
q.pop();
now=temp->right;
}
return ans;
}
};
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> ans;
TreeNode* now=root;
while(now||!st.empty()){
while(now){
st.emplace(now);
now=now->left;
}
TreeNode* temp=st.top();
st.pop();
ans.push_back(temp->val);
// 已经遍历过的结点不会再遍历一次
// 切到右结点
temp=temp->right;
now=temp;
}
return ans;
}
};
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> ans;
TreeNode* now=root;
// prev等于出栈的元素
TreeNode* prev=nullptr;
while(now||!st.empty()){
while(now){
st.emplace(now);
now=now->left;
}
TreeNode* temp=st.top();
st.pop();
if(temp->right==nullptr||temp->right==prev){
prev=temp;
ans.push_back(temp->val);
now=nullptr;
}else{
st.push(temp);
now=temp->right;
}
}
return ans;
}
};