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;
        }
    }
相关推荐
地平线开发者17 小时前
征程6|YOLOv5x 在 Horizon 征程6 上的端到端部署实践(下)
算法·自动驾驶
speop18 小时前
llm-algo-leetcode |Task01
算法·leetcode·职场和发展
艾为电子18 小时前
【应用方案】电视沉浸式音频升级: 电视音频 awinic“芯片 + 算法” 一体化解决方案
算法·音视频
大熊背18 小时前
树莓派相机自动白平衡详解(二)
算法·白平衡·isppipeline
Scabbards_18 小时前
面试Leetcode - 算法合集
算法·leetcode·面试
chuan.bai18 小时前
Java RAG 实战附录:qwen3 与 bge-m3 模型切换指南
java·人工智能·算法
wuyk55518 小时前
7.AVL 树:第一个自平衡二叉搜索树
开发语言·stm32·单片机·算法
程序猿炎义18 小时前
【llm-algo-leetcode学习笔记】显存与性能认知底座
笔记·学习·leetcode
rannn_11118 小时前
【力扣hot100】二叉树专题+总结
java·算法·leetcode·二叉树
啊嘞嘞?19 小时前
力扣(岛屿数量)
算法·leetcode