-
题目
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
相关推荐
还有多久拿退休金1 小时前
让飞书知识库跟着 commit 自己长:一套自动化知识库的真实实现KaMeidebaby2 小时前
卡梅德生物技术快报|小 RNA 适配体合成 + 多方法亲和力表征全流程标准化操作手册是Dream呀2 小时前
基于深度学习的人类行为识别算法研究happyprince3 小时前
03_NVIDIA_ModelOpt-量化算法深入大鱼>3 小时前
AI+货物追踪:智能快递柜追踪系统researcher-Jiang4 小时前
算法训练:堆 & 可并堆在书中成长4 小时前
HarmonyOS 小游戏《对战五子棋》开发第18篇 - 棋盘设计Frostnova丶4 小时前
(12)LeetCode 76. 最小覆盖子串灯澜忆梦5 小时前
GO_函数_1言乐65 小时前
Python实现建造微服务商城后台