NeetCode #382LC-94EasyTreesNC 250
← Back to All Problems#382 · #94 · Binary Tree Inorder Traversal(二叉树的中序遍历)
📌 Problem Statement & Constraints
Given the root of a binary tree, return its in-order traversal (left, root, right) as a list of values. Constraints: the number of nodes is in
[0, 100]. The follow-up asks for an iterative solution.💡 Core Algorithmic Approaches
- The iterative form uses an explicit stack: descend to the leftmost node, pushing as you go.
- Pop and visit, then move to the right child and repeat the descent.
- The loop continues while either the stack is non-empty or the current pointer is non-null.
- This is the same skeleton used for the K-th smallest element in a BST and for the BST iterator.
💻 Benchmark Python3 Implementation
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
st = []
cur = root
while cur or st:
while cur: # descend to the leftmost node
st.append(cur)
cur = cur.left
cur = st.pop() # visit
res.append(cur.val)
cur = cur.right # then the right subtree
return res
# Morris traversal: O(1) space using temporary threads
class Solution2:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
cur = root
while cur:
if not cur.left:
res.append(cur.val)
cur = cur.right
else:
# find the in-order predecessor
pred = cur.left
while pred.right and pred.right is not cur:
pred = pred.right
if not pred.right:
pred.right = cur # create a temporary thread
cur = cur.left
else:
pred.right = None # remove the thread
res.append(cur.val)
cur = cur.right
return res⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n) for both variants (Morris is O(n) amortised despite the inner loop).
💾 Space Complexity
O(h) for the stack; O(1) for Morris traversal.
⚠️ Interview Pitfalls & Follow-ups
- Looping only
while cur: nodes left on the stack after the left descent would be skipped; the condition must bewhile cur or st. - Forgetting
cur = cur.right: the traversal would revisit the same node indefinitely. - Using recursion for a deep tree: the stack depth can reach n.
- Morris traversal forgetting to remove the temporary thread: the tree would be corrupted and the traversal would loop.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Trees Problems
中文速览与面试要点
二叉树的中序遍历
给定一个二叉树的根节点 root,返回 它的中序遍历 。进阶:递归算法很简单,你可以通过迭代算法完成吗?约束:树中节点数目在范围 [0, 100] 内;-100 ≤ Node.val ≤ 100。
核心要点
- 递归(最直观) : 左子树 → 根 → 右子树 。
- 迭代 + 栈(标准解法) :用一个指针 cur 从根出发,一路向左压栈;无法继续时弹出栈顶(访问),然后转向其右子树。
- 为什么这样能模拟中序 :栈中保存的是「已发现但尚未访问」的节点,且自底向上依次是「更深的左节点」——弹出顺序恰好是「左 → 根」。
- Morris 遍历(O(1) 空间) :利用叶子节点的空右指针建立临时线索,可做到 O(1) 额外空间,但会临时修改树结构。
常见陷阱
- 循环条件写成 while cur :会漏掉「cur 为 None 但栈非空」的情况(此时需要弹栈)。必须用 while cur or stack 。
- 先 res.append 再转向左子树 :那是前序。中序必须「先走完左子树,再访问根」。
- 忘记 cur = cur.right :会死循环。
- 递归版本在链状树上栈溢出 :n ≤ 100 时安全。
参考实现
class Solution:
def inorderTraversal(self, root: 'TreeNode') -> list[int]:
# 迭代 + 栈
res = []
stack = []
cur = root
while cur or stack:
while cur: # 一路向左
stack.append(cur)
cur = cur.left
cur = stack.pop() # 弹出即访问
res.append(cur.val)
cur = cur.right # 转向右子树
return res
# 递归版本
# def inorderTraversal(self, root):
# if not root: return []
# return (self.inorderTraversal(root.left)
# + [root.val]
# + self.inorderTraversal(root.right))