当前位置: 首页 > article >正文

11.递归遍历、迭代遍历、统一迭代、层序遍历

递归算法

三要素

  • 参数和返回值
  • 终止条件
  • 单层返回逻辑

例题

leetcode:

  • 144.二叉树的前序遍历(opens new window)
  • 145.二叉树的后序遍历(opens new window)
  • 94.二叉树的中序遍历

迭代遍历

递归的本质还是利用栈实现的,所以我们可以配合栈来实现迭代遍历

前序遍历

先压入root;

root出栈时,压入右左节点,然后重复该过程直到栈空。

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

        stack<TreeNode*> Mysta;
        if(root)Mysta.push(root);
        while(!Mysta.empty()){
            TreeNode* cur=Mysta.top();
            Mysta.pop();
            if(cur->right)Mysta.push(cur->right);
            if(cur->left)Mysta.push(cur->left);
            res.push_back(cur->val);
        }
        return res;
    }
    
};

中序遍历

中序遍历不能直接改编前序遍历;

把左边一支全部压栈;

然后吐出栈顶为cur,处理完后,将当cur的右节点以及左边的一支压入

class Solution {
public:
    
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> Mysta;
        TreeNode* cur=root;
        while(cur){
            Mysta.push(cur);
            cur=cur->left;            
        }
        while(!Mysta.empty()){
            cur=Mysta.top();
            Mysta.pop();
            if(cur->right){
                TreeNode* tmp=cur->right;
                
                while(tmp){
                    Mysta.push(tmp);
                    tmp=tmp->left;
                }
            }
            res.push_back(cur->val);
        }
        return res;
    }
};

后序遍历

后序遍历可以通过镜像的先序遍历,然后反转整个结果得到。

class Solution {
public:
    
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> stack;
        if(root)
        stack.push(root);
        while(!stack.empty()){
            TreeNode* cur=stack.top();
            stack.pop();
            res.push_back(cur->val);
            if(cur->left)stack.push(cur->left);
            if(cur->right)stack.push(cur->right);
            
        }
        reverse(res.begin(),res.end());
        return res;
    }
};

统一迭代

层序遍历

队列


http://www.kler.cn/a/538852.html

相关文章:

  • MySQL下载过程
  • IDEA中Resolving Maven dependencies卡着不动解决方案
  • 电脑黑屏按什么键恢复?电脑黑屏的解决办法
  • 视频采集卡接口
  • 疯狂前端面试题(二)
  • 响应式编程_05 Project Reactor 框架
  • Excel大数据量导入导出
  • React 生命周期函数详解
  • antd-react日期组件disabledDate不可选择的日期 (置灰)属性
  • Nginx进阶篇 - nginx多进程架构详解
  • SpringBoot速成(八)登录实战:未登录不能访问 P5-P8
  • Vue 3 + Vite + JS 项目中实现组件全局自动化注册的魔法,极致组件自动化注册方案,开发效率飙升300%。
  • linux 基础知识点之工作队列workqueue
  • (done) openMP学习 (Day9: 优化链表操作)
  • DeepSeek介绍,以及本地部署和API使用
  • 内容中台赋能人工智能技术提升业务创新能力
  • Jenkins 使用教程:从入门到精通
  • 如何使用JLINK连接雅特力MCU
  • Ada语言的云计算
  • LeetCode 力扣热题100 将有序数组转换为二叉搜索树
  • fps动作系统7:武器摇摆
  • 人工智能应用实例-自动驾驶A*算法高级应用
  • LS-SDMTSP:粒子群优化算法(PSO)求解大规模单仓库多旅行商问题(LS-SDMTSP),MATLAB代码
  • 写综述小论文的反思
  • 2.9寒假作业
  • 将DeepSeek接入Excel实现交互式对话