-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path二叉树的迭代遍历
75 lines (72 loc) · 1.82 KB
/
二叉树的迭代遍历
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
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) { // 前序遍历
stack<TreeNode*> st;
if (root) {
st.push(root);
}
vector<int> result;
while(st.empty()==0){
TreeNode *n=st.top();
result.push_back(n->val);
st.pop();
if(n->right) st.push(n->right);
if(n->left) st.push(n->left);
}
return result;
}
};
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) { // 中序遍历
vector<int> result;
stack<TreeNode*> st;
if(root==NULL) return {};
st.push(root);
while(!st.empty()){
TreeNode* n=st.top();
st.pop();
if(n->right){
st.push(n->right);
n->right=NULL;
}
if(n->left==NULL){
result.push_back(n->val);
}
else{
st.push(n);
st.push(n->left);
n->left=NULL;
}
}
return result;
}
};
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) { // 后序遍历
vector<int> result;
stack<TreeNode*> st;
if(root==NULL) return {};
st.push(root);
while(!st.empty()){
TreeNode* n=st.top();
st.pop();
if(n->left==NULL&&n->right==NULL){
result.push_back(n->val);
}
else{
st.push(n);
if(n->right){
st.push(n->right);
n->right=NULL;
}
if(n->left){
st.push(n->left);
n->left=NULL;
}
}
}
return result;
}
};