-
题目
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
相关推荐
Tiny番茄11 分钟前
归一化函数 & 激活函数jz_ddk24 分钟前
[学习] RTKLib详解:rtcm2.c、rtcm3.c、rtcm3e与rtcmn.c小学生的信奥之路1 小时前
力扣1991:找到数组的中间位置(前缀和)এ᭄画画的北北1 小时前
力扣-102.二叉树的层序遍历ccLianLian1 小时前
数据结构·字典树JeffersonZU3 小时前
【数据结构】1-4算法的空间复杂度L_cl3 小时前
【Python 算法零基础 4.排序 ① 选择排序】山北雨夜漫步4 小时前
机器学习 Day18 Support Vector Machine ——最优美的机器学习算法拼好饭和她皆失4 小时前
算法加训之最短路 上(dijkstra算法)瓦力wow6 小时前
c语言 写一个五子棋