二叉树的三种遍历 (递归+迭代)

前言:真的好久没有写博客了。最近也到春招季了,想必很多小伙伴在准备面试了,因此想着来写一篇关于二叉树遍历的博客。同时也希望大家:山水万程,皆有好运!


定义树结构:

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

递归版本:

  • 普通写法
void dfs(TreeNode *root){
    if(!root)
        return;
    // Preorder
    dfs(root->left);
    // Inorder
    dfs(root->right);
    // Postorder
}
  • C++的 Lambda 写法
void solve(TreeNode *root) {
    auto dfs = [&](auto self, TreeNode *rt) -> void{
       if(!root)
        	return;
        // Preorder
        self(self, rt->left);
        // Inorder
        self(self, rt->right);
        // Postorder
    };

    dfs(dfs, rt);
}

迭代版本:

  • 前序遍历
vector<int> preOrder(TreeNode *root) {
    vector<int> order;
    if(!root){
        return ;
    }
    
    stack<TreeNode *> s;
    s.push(root);
    
    while(s.size()){
        TreeNode *cur = s.top();
        s.pop();
        order.emplace_back(cur->val);
        
        if(cur->right){
            s.push(cur->right);
        }
        if(cur->left){
            s.push(cur->left);
        }
    }
    
    return order;
}
  • 中序遍历
vector<int> inOrder(TreeNode *root) {
    vector<int> order;
    if(!root)
        return order;
    
    unordered_set<TreeNode *> vis;
    stack<TreeNode *> s;
    
    s.push(root);
    while(s.size()){
        TreeNode *cur = s.top();
        if(vis.count(cur)){
            order.emplace_back(cur->val);
            s.pop();
            if(cur->right)
                s.push(cur->right);
        }else{
            vis.emplace(cur);
            if(cur->left)
                s.push(cur->left);
        }
    }
    
    return order;
}
  • 后序遍历
vector<int> postOrder(TreeNode *root) {
    vector<int> order;

    if(!root)
        return order;

    unordered_set<TreeNode *> vis;
    stack<TreeNode *> s;
    
    s.push(root);
    while(s.size()){
        TreeNode *cur = s.top();
        
        if((!cur->left and !cur->right) || vis.count(cur)){
            order.emplace_back(cur->val);
            s.pop();
        }else{
            vis.emplace(cur);
            if(cur->right)
                s.push(cur->right);
            if(cur->left)
                s.push(cur->left);
        }
    }
    return order;
}


以上就是这篇博客的全部内容,若内容有误,欢迎大家指出!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值