-
题目
java给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。 -
示例
java示例 1 输入:root = [1,null,2,3] 输出:[1,3,2] 示例 2: 输入:root = [] 输出:[] 示例 3: 输入:root = [1] 输出:[1] -
解题思路
- 方法一:递归。
- 方法二:循环。
- 使用栈保存根节点。
- 每次从栈中取出当前根节点,并将其左右子节点,加入栈中。
-
代码(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; } }javaclass 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; } }
LeetCode94 二叉树的中遍历
biglxl2024-03-10 19:35
相关推荐
纪念 2297 分钟前
C++ 算法模板与错题 (高精度)Navigator_Z1 小时前
LeetCode //C - 1331. Rank Transform of an ArrayTisfy1 小时前
LeetCode 1202.交换字符串中的元素:分组排序(连通图)csdn_aspnet8 小时前
C++ 使总距离最短的最佳点位置(Optimum location of point to minimize total distance)逐米时代11 小时前
「制造新解法」行业对标方法:借鉴而不照搬的最佳实践kyrie_sakura11 小时前
大模型学习32 --大模型微调3 -- 分布式训练算法Rabitebla12 小时前
【Linux】 文件系统(五):挂载与软硬链接,多个文件系统怎样组成统一目录树m0_7431064612 小时前
SAD-GS:从梯度邻域到频率驱动表达3D空间csdn_aspnet13 小时前
Java 使总距离最短的最佳点位置(Optimum location of point to minimize total distance)专注仿真14 小时前
仿真智能体训练(评估指标篇):任务完成率算法详解与实战