-
题目
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
相关推荐
MicroTech202515 小时前
微算法科技(NASDAQ: MLGO)采用量子相位估计(QPE)方法,增强量子神经网络训练星梦清河15 小时前
宋红康 JVM 笔记 Day15|垃圾回收相关算法货拉拉技术15 小时前
揭秘语音交互的核心技术矛取矛求16 小时前
日期类的实现在下雨59916 小时前
项目讲解1Jayyih16 小时前
嵌入式系统学习Day36(简单的网页制作)脑洞代码17 小时前
20250909的学习笔记Christo317 小时前
TFS-2003《A Contribution to Convergence Theory of Fuzzy c-Means and Derivatives》黑菜钟17 小时前
代码随想录第七天|● 454.四数相加II ● 383. 赎金信 ● 15. 三数之和 18.四数之和Yingjun Mo17 小时前
1. 统计推断-ALMOND收敛性分析