-
题目
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 小时前
SparseDrive 模型导出与性能优化实战董董灿是个攻城狮2 小时前
大模型连载2:初步认识 tokenizer 的过程地平线开发者2 小时前
地平线 VP 接口工程实践(一):hbVPRoiResize 接口功能、使用约束与典型问题总结罗西的思考2 小时前
AI Agent框架探秘:拆解 OpenHands(10)--- RuntimeHXhlx6 小时前
CART决策树基本原理Wect6 小时前
LeetCode 210. 课程表 II 题解:Kahn算法+DFS 双解法精讲颜酱7 小时前
单调队列:滑动窗口极值问题的最优解(通用模板版)Gorway13 小时前
解析残差网络 (ResNet)拖拉斯旋风14 小时前
LeetCode 经典算法题解析:优先队列与广度优先搜索的巧妙应用Wect14 小时前
LeetCode 207. 课程表:两种解法(BFS+DFS)详细解析