Leetcode Binary Tree

本文介绍了如何使用递归和迭代方法来遍历二叉树,包括前序、中序和后序遍历。在递归方法中,通过反转子树顺序实现了前序和后序遍历。而在迭代方法中,利用栈进行操作,特别是后序遍历需要在遍历完成后反转结果数组。

二叉树的递归遍历

  1. 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;   
    }
  1. 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. 迭代

  1. 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;
    }
};
  1. 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;
    }
};
  1. 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;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值