前序遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
vector<int> preorderTraversal(TreeNode* root) {
if(!root) return {};
vector<int> result;
stack<TreeNode*> stk;
stk.push(root);
while(!stk.empty()){
TreeNode* node = stk.top();
stk.pop();
if(node){
if(node -> right){
stk.push(node -> right);
}
if(node -> left){
stk.push(node -> left);
}
stk.push(node);
stk.push(nullptr);
}else{
result.push_back(stk.top()->val);
stk.pop();
}
}
return result;
}

中序遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
vector<int> inorderTraversal(TreeNode* root) {
if(!root) return {};
vector<int> result;
stack<TreeNode*> stk;
stk.push(root);
while(!stk.empty()){
TreeNode* node = stk.top();
stk.pop();
if(node){
if(node -> right){
stk.push(node -> right);
}
stk.push(node);
stk.push(nullptr);
if(node -> left){
stk.push(node -> left);
}
}else{
result.push_back(stk.top()->val);
stk.pop();
}
}
return result;
}

后序遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
vector<int> postorderTraversal(TreeNode* root) {
if(!root) return {};
vector<int> result;
stack<TreeNode*> stk;
stk.push(root);
while(!stk.empty()){
TreeNode* node = stk.top();
stk.pop();
if(node){
stk.push(node);
stk.push(nullptr);
if(node -> right){
stk.push(node -> right);
}
if(node -> left){
stk.push(node -> left);
}
}else{
result.push_back(stk.top()->val);
stk.pop();
}
}
return result;
}