二叉树的递归遍历
preorder(Leetcode 144)
public:
vector<int> res;
void reverse(TreeNode *cur){
if(cur == NULL) return;
res.push_back(cur->val);
reverse(cur->left);
reverse(cur->right);
}
vector<int> preorderTraversal(TreeNode* root) {
reverse(root);
return res;
}postorder(Leetcode 145)
class Solution {
public:
vector<int> res;
void reverse(TreeNode *cur){
if(cur == NULL) return;
reverse(cur->left);
reverse(cur->right);
res.push_back(cur->val);
}
vector<int> postorderTraversal(TreeNode* root) {
reverse(root);
return res;
}
};3. Inorder(Leetcode 94)
class Solution {
public:
vector<int> res;
void reverse(TreeNode *cur){
if(cur == NULL) return;
reverse(cur->left);
res.push_back(cur->val);
reverse(cur->right);
}
vector<int> inorderTraversal(TreeNode* root) {
reverse(root);
return res;
}
};2. 迭代
preorder
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> stk;
stk.push(root);
if(root == NULL)
return res;
while(!stk.empty()){
TreeNode *cur = stk.top();
stk.pop();
res.push_back(cur->val);
if(cur->right) stk.push(cur->right);
if(cur->left) stk.push(cur->left);
}
return res;
}
};postorder
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> stk;
if(root == NULL) return res;
stk.push(root);
while(!stk.empty()){
TreeNode *cur = stk.top();
res.push_back(cur->val);
stk.pop();
if(cur->left) stk.push(cur->left);
if(cur->right) stk.push(cur->right);
}
reverse(res.begin(), res.end());
return res;
}
};inorder
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> stk;
TreeNode *cur = root;
while(cur != NULL || !stk.empty()){
if(cur != NULL){
stk.push(cur);
cur = cur->left;
}else{
cur = stk.top();
res.push_back(cur->val);
stk.pop();
cur = cur->right;
}
}
return res;
}
};
本文介绍了如何使用递归和迭代方法来遍历二叉树,包括前序、中序和后序遍历。在递归方法中,通过反转子树顺序实现了前序和后序遍历。而在迭代方法中,利用栈进行操作,特别是后序遍历需要在遍历完成后反转结果数组。
1355

被折叠的 条评论
为什么被折叠?



