-
题目
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
相关推荐
shirsl5 小时前
算法 Day1-数组 / 哈希 + 双指针2601_9677607812 小时前
2026年PDF压缩与页码添加工具技术实测:性能、算法与本地化适配深度对比不会就选b12 小时前
算法日常・每日刷题--<贪心>7moonrailgun13 小时前
用 Node.js 复刻 Codex Astra 的终端星光罗西的思考13 小时前
[Agent Memory / 强化学习] MemPO源码学习笔记 ---(1)--- 总体lvwangshu14 小时前
图论:LCA、树的直径、树的重心、二分图与 Tarjan 缩点302wanger15 小时前
干与湿:AI 拿走脑力之后,人剩下什么计算机编程-吉哥16 小时前
脑肿瘤MRI智能识别系统:基于深度学习的像素级脑肿瘤语义分割平台【计算机毕业设计选题推荐】用户2049375549516 小时前
端侧语音部署踩坑:模型能跑不等于终端真的能用shehuiyuelaiyuehao16 小时前
算法39,位运算,消失的两个数字