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

LeetCode--二叉树前中后遍历(迭代遍历)

二叉树前中后遍历(迭代遍历)

前序遍历
public List<Integer> preorderTraversal(TreeNode root) {
    List<Integer> res = new ArrayList<>();
    if (root == null) return res;
    Stack<TreeNode> stack = new Stack<>();
    stack.push(root);
    while (!stack.isEmpty()) {
        TreeNode node = stack.pop();
        res.add(node.val);
        //先右后左
        if (node.right != null) stack.push(node.right);
        if (node.left != null) stack.push(node.left);
    }
    return res;
}
中序遍历
public List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> res = new ArrayList<>();
    if (root == null) return res;
    Stack<TreeNode> stack = new Stack<>();
    TreeNode cur = root;
    while (cur != null || !stack.isEmpty()) {
        //找最左边的节点
        while (cur != null) {
            stack.push(cur);
            cur = cur.left;
        }
        //弹出栈顶,访问
        cur = stack.pop();
        res.add(cur.val);
        //找右节点
        cur = cur.right;
    }
    return res;
}
后序遍历
//后序遍历相当于先序遍历的逆序
public List<Integer> postorderTraversal(TreeNode root) {
    List<Integer> res = new ArrayList<>();
    if (root == null) return res;
    Stack<TreeNode> stack = new Stack<>();
    stack.push(root);
    while (!stack.isEmpty()) {
        TreeNode cur = stack.pop();
        res.add(cur.val);
        if (cur.left != null) stack.push(cur.left);
        if (cur.right != null) stack.push(cur.right);
    }
    // 反转
    return res.reversed();
}

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

相关文章:

  • hot100_23. 合并 K 个升序链表
  • PT8042 双触控双输出触摸 IC
  • chrome-mojo C++ Bindings API
  • 使用 Apifox、Postman 测试 Dubbo 服务,Apache Dubbo OpenAPI 即将发布
  • (篇六)基于PyDracula搭建一个深度学习的软件之新版本ultralytics-8.3.28调试
  • AI与大数据融合:技术路径与行业赋能
  • 实操部署DeepSeek,添加私有知识库
  • 【Unity3D】Unable to detect SDK in the selected directory
  • 基于单片机的电子式单项智能电表设计(论文+源码)
  • AF3 superimpose函数解读
  • 持久性HTTPVS.非持久性HTTP
  • ASP.NET Core用MediatR实现领域事件
  • 2025年02月11日Github流行趋势
  • MySQL的字符集(Character Set)和排序规则(Collation)
  • JavaScript中Map和Set数据结构详解
  • Gitlib 企业本地部署
  • docker compose部署flink集群
  • 盛铂科技SWFA100捷变频频率综合器:高性能国产射频系统的关键选择
  • Vue前端开发-Pinia其他扩展插件
  • android 安装第三方apk自动赋予运行时权限
  • OSPF高级特性(3):安全特效
  • 【Java并发编程之如何在线程中安全地访问一个全局Boolean类型的静态变量?】
  • 详解spotbugs -textui常用命令(包括生成html测试报告)
  • Vue.js 响应式原理与数据绑定
  • 4. React 中的 CSS
  • Visual Studio 中的键盘快捷方式