LeetCode 94. 二叉树的中序遍历
题目描述
给定一个二叉树,返回它的中序遍历。
示例 1:
输入:root = [1,null,2,3]
输出:[1,3,2]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
提示: 树中节点数目在范围 [0, 10000]
内,且 -100 <= Node.val <= 100
。
Java 实现解法
方法一:递归
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
class Solution {public List<Integer> inorderTraversal(TreeNode root) {List<Integer> result = new ArrayList<>();inorder(root, result);return result;}private void inorder(TreeNode node, List<Integer> result) {if (node == null) return;inorder(node.left, result);result.add(node.val);inorder(node.right, result);}
}
方法二:迭代(使用栈)
class Solution {public List<Integer> inorderTraversal(TreeNode root) {List<Integer> result = new ArrayList<>();Stack<TreeNode> stack = new Stack<>();TreeNode curr = root;while (curr != null || !stack.isEmpty()) {while (curr != null) {stack.push(curr);curr = curr.left;}curr = stack.pop();result.add(curr.val);curr = curr.right;}return result;}
}
解题思路
-
递归方法:
- 对根节点进行中序遍历,首先递归遍历左子树,然后访问根节点,最后递归遍历右子树。
- 这种方法利用了递归调用的自然特性,每次递归到叶子节点时,自动完成中序遍历的“左-根-右”顺序。
-
迭代方法:
- 使用栈来模拟递归过程。
- 从根节点开始,向左遍历到最深,每遍历到一个节点就将其压入栈中。
- 当无法继续向左遍历时,弹出栈顶节点并访问它,然后转向右子树。
- 重复此过程直到栈为空且当前节点为
null
。
时间复杂度
- 时间复杂度:O(n),其中 n 是树中节点的数量。每个节点恰好被访问一次。
空间复杂度
- 空间复杂度:
- 递归方法:O(n),递归栈在最坏情况下可能需要存储 n 个节点。
- 迭代方法:O(n),栈在最坏情况下可能需要存储 n 个节点(当树完全不平衡时,如链状结构)。