NeetCode #383LC-144EasyTreesNC 250
← Back to All Problems#383 · #144 · Binary Tree Preorder Traversal(二叉树的前序遍历)
📌 Problem Statement & Constraints
Given the root of a binary tree, return its pre-order traversal (root, left, 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
- Push the root, then repeatedly pop and visit.
- Push the right child before the left, so the left is popped first and processed next.
- This one-stack formulation is the simplest iterative pre-order traversal.
- An alternative pushes only the left spine and uses the stack for the right subtrees, which generalises to the other orders.
💻 Benchmark Python3 Implementation
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
res = []
st = [root]
while st:
node = st.pop()
res.append(node.val)
# push right first so left is processed first
if node.right:
st.append(node.right)
if node.left:
st.append(node.left)
return res⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): each node is pushed and popped once.
💾 Space Complexity
O(h) for the stack in the best case, O(n) in the worst case.
⚠️ Interview Pitfalls & Follow-ups
- Pushing left before right: the traversal order would become root, right, left.
- Recursing without a depth guard: a degenerate tree would exhaust the recursion limit.
- Forgetting the empty-tree check:
st = [root]withroot = Nonewould crash onnode.val. - Assuming the output is sorted: pre-order is determined by the tree structure, not by value.
⚡
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。
核心要点
- 递归(最直观) : 根 → 左子树 → 右子树 。
- 迭代 + 栈 :先把根入栈;每次弹出栈顶并访问,然后 先压右子节点、再压左子节点 (因为栈是后进先出,这样才能先访问左子树)。
- 为什么压栈顺序要反 :要保证左子树先被处理,因此左子节点必须后压(在栈顶)。
- 另一种迭代写法 :模拟递归的「一路向左」过程(与中序类似,只是访问时机在压栈时)。
常见陷阱
- 先压左子节点再压右子节点 :会导致右子树先被处理,得到「根 → 右 → 左」的错误顺序。必须 先压右、后压左 。
- 忘记处理空树 :返回空列表。
- 用队列而非栈 :会变成层序遍历。
参考实现
class Solution:
def preorderTraversal(self, root: 'TreeNode') -> list[int]:
if not root:
return []
res = []
stack = [root]
while stack:
node = stack.pop()
res.append(node.val) # 弹出即访问
# 先压右、再压左,保证左子树先被处理
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return res
# 递归版本
# def preorderTraversal(self, root):
# if not root: return []
# return ([root.val]
# + self.preorderTraversal(root.left)
# + self.preorderTraversal(root.right))