LeetCode 题解工作台
二叉树的中序遍历
给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。 示例 1: 输入: root = [1,null,2,3] 输出: [1,3,2] 示例 2: 输入: root = [] 输出: [] 示例 3: 输入: root = [1] 输出: [1] 提示: 树中节点数目在范围 [0, 10…
4
题型
7
代码语言
3
相关题
当前训练重点
简单 · 二分·树·traversal
答案摘要
我们先递归左子树,再访问根节点,接着递归右子树。 时间复杂度 ,空间复杂度 。其中 是二叉树的节点数,空间复杂度主要取决于递归调用的栈空间。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。
示例 1:
输入:root = [1,null,2,3] 输出:[1,3,2]
示例 2:
输入:root = [] 输出:[]
示例 3:
输入:root = [1] 输出:[1]
提示:
- 树中节点数目在范围
[0, 100]内 -100 <= Node.val <= 100
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
解题思路
方法一:递归遍历
我们先递归左子树,再访问根节点,接着递归右子树。
时间复杂度 ,空间复杂度 。其中 是二叉树的节点数,空间复杂度主要取决于递归调用的栈空间。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
def dfs(root):
if root is None:
return
dfs(root.left)
ans.append(root.val)
dfs(root.right)
ans = []
dfs(root)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Do you know why inorder on [1,null,2,3] must delay visiting 2 until after processing 3?
- question_mark
Can you explain how your traversal keeps track of where to return after finishing a left subtree?
- question_mark
Will you switch from recursion or a stack to Morris traversal if constant extra space is requested?
常见陷阱
外企场景- error
Appending a node value before fully traversing its left subtree, which turns the result into preorder-like output instead of inorder.
- error
After popping a node from the stack, forgetting to move to its right child, which causes entire right-side segments to be skipped.
- error
Implementing Morris traversal without restoring predecessor.right to null, leaving threads behind and producing duplicate visits or a modified tree.
进阶变体
外企场景- arrow_right_alt
Return the preorder traversal of the same binary tree using recursive, iterative, or Morris-style traversal changes.
- arrow_right_alt
Return the postorder traversal, where the state-tracking becomes harder because the node is recorded after both subtrees.
- arrow_right_alt
Implement inorder traversal iteratively without recursion, then explain how the answer changes if the interviewer requires O(1) extra space.