-
题目
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
相关推荐
Bear on Toilet3 分钟前
12 . 二叉树的直径惜.己5 分钟前
数据结构与算法-数组异或操作2301_807997388 分钟前
代码随想录-day55程序员东岸10 小时前
《数据结构——排序(中)》选择与交换的艺术:从直接选择到堆排序的性能跃迁程序员-King.10 小时前
day104—对向双指针—接雨水(LeetCode-42)神仙别闹10 小时前
基于C++实现(控制台)应用递推法完成经典型算法的应用Ayanami_Reii10 小时前
进阶数据结构应用-一个简单的整数问题2(线段树解法)listhi52011 小时前
基于改进SET的时频分析MATLAB实现Keep_Trying_Go12 小时前
基于Zero-Shot的目标计数算法详解(Open-world Text-specified Object Counting)