AcWing
  • 首页
  • 题库
  • 题解
  • 分享
  • 问答
  • 活动
  • 应用
  • 吐槽
  • 登录/注册

二叉树的遍历

作者: 作者的头像   Lion ,  2021-01-11 11:39:50 ,  阅读 41


0


1

递归版本

class Solution {
public:
    vector<int> res;
    vector<int> preorderTraversal(TreeNode* root) {
        dfs(root);
        return res;
    }

    // 前序
    void dfs(TreeNode* root){
        if(!root) return;
        res.push_back(root->val);
        dfs(root->left);
        dfs(root->right);
    }

   // 中序
    void dfs(TreeNode* root){
        if(!root) return;
        dfs(root->left);
        res.push_back(root->val);
        dfs(root->right);
    }

    // 后序
    void dfs(TreeNode* root){
        if(!root) return;
        dfs(root->left);
        dfs(root->right);
        res.push_back(root->val);
    }
};

递归容易,遍历不好理解。这里总结下,前中后类似,后序多一个prev表示之前遍历过的节点


struct TreeNode {
     int val;
     TreeNode *left;
     TreeNode *right;
     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
// 前序
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> stk;
        while (root || stk.size()) {
            while (root) {
                res.push_back(root->val);  //前序在进栈前add value
                stk.push(root);
                root = root->left;
            }
            root = stk.top();
            stk.pop();

            root = root->right;
        }
        return res;
    }
};

//中序
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> stk;
        while(root || stk.size()){
            while(root) {
                stk.push(root);
                root = root -> left;
            }
            root = stk.top();
            stk.pop();

            res.push_back(root->val); //中序出栈后,add value
            root = root->right;
        }
        return res;
    }
};

//后序
class Solution {
public:
    vector<int> res;
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        if(!root) return res;
        stack<TreeNode*> stk;
        TreeNode* prev = nullptr;//后序遍历需要额外的 prev指针,表示上次加入res的节点
        while(root || stk.size()){
            while(root) {
                stk.push(root);
                root = root -> left;
            }
            root = stk.top();
            stk.pop();

            //root不存在右节点,或者,root右节点上次已经遍历了(prev代表上次已add)
            if(!root->right||root->right == prev){
                res.push_back(root->val);
                prev = root;
                root = nullptr;
            } else { // 存在右节点,且还未被遍历,则先入栈
                stk.push(root);
                root = root->right;
            }
        }
        return res;
    }
};

0 评论

你确定删除吗?

© 2018-2021 AcWing 版权所有  |  京ICP备17053197号-1
联系我们  |  常见问题
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标
请输入绑定的邮箱地址
请输入注册信息