LeetCode94 二叉树的中遍历

  1. 题目

    java 复制代码
    给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。
  2. 示例

    java 复制代码
    示例 1
    输入:root = [1,null,2,3]
    输出:[1,3,2]
    
    示例 2:
    输入:root = []
    输出:[]
    
    示例 3:
    输入:root = [1]
    输出:[1]
  3. 解题思路

    1. 方法一:递归。
    2. 方法二:循环。
      1. 使用栈保存根节点。
      2. 每次从栈中取出当前根节点,并将其左右子节点,加入栈中。
  4. 代码(Java)

    java 复制代码
     // 方法一
    class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> res = new ArrayList<>();
            midTrav(res, root);
            return res;
        }
        public Integer midTrav(List<Integer> res, TreeNode root) {
            if (root != null) {
                Integer left = midTrav(res, root.left);
                if (left != null) {
                    res.add(left);
                }
                res.add(root.val);
                Integer right = midTrav(res, root.right);
                if (right != null) {
                    res.add(right);
                }
            }
            return null;
        }
    }
    java 复制代码
    class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> res = new ArrayList<>();
            if (root == null) {
                return res;
            }
            Stack<TreeNode> stack = new Stack<TreeNode>();
            while (root != null || !stack.isEmpty()) {
                if (root != null) {
                    stack.push(root);
                    root = root.left;
                } else {
                    root = stack.pop();
                    res.add(root.val);
                    root = root.right;
                }
            }
            return res;
        }
    }
相关推荐
shirsl5 小时前
算法 Day1-数组 / 哈希 + 双指针
python·算法·哈希算法
2601_9677607812 小时前
2026年PDF压缩与页码添加工具技术实测:性能、算法与本地化适配深度对比
算法·pdf
不会就选b12 小时前
算法日常・每日刷题--<贪心>7
数据结构·算法·leetcode
moonrailgun13 小时前
用 Node.js 复刻 Codex Astra 的终端星光
前端·javascript·算法
罗西的思考13 小时前
[Agent Memory / 强化学习] MemPO源码学习笔记 ---(1)--- 总体
人工智能·算法·机器学习
lvwangshu14 小时前
图论:LCA、树的直径、树的重心、二分图与 Tarjan 缩点
算法·图论
302wanger15 小时前
干与湿:AI 拿走脑力之后,人剩下什么
算法
计算机编程-吉哥16 小时前
脑肿瘤MRI智能识别系统:基于深度学习的像素级脑肿瘤语义分割平台【计算机毕业设计选题推荐】
人工智能·python·深度学习·算法·毕业设计·课程设计·大数据毕业设计选题推荐
用户2049375549516 小时前
端侧语音部署踩坑:模型能跑不等于终端真的能用
后端·算法
shehuiyuelaiyuehao16 小时前
算法39,位运算,消失的两个数字
java·数据结构·算法