NeetCode #399LC-314MediumTreesNC Algo100
← Back to All Problems#399 · #314 · Binary Tree Vertical Order Traversal(二叉树的垂序遍历)
📌 Problem Statement & Constraints
Given the root of a binary tree, return its vertical order traversal: a list of columns from leftmost to rightmost, where each column lists the node values top to bottom. Within a column, nodes at the same depth are ordered left to right. Constraints: the number of nodes is in
[0, 1000].💡 Core Algorithmic Approaches
- Assign each node a column index: the root is 0, the left child is
column - 1, the right childcolumn + 1. - BFS is essential here, because it guarantees that nodes are appended in top-to-bottom order, and left-to-right within the same depth.
- Collect the values into a map from column to list, then emit the columns in ascending order.
- A DFS would need an extra sort key of
(depth, order)to reproduce the same ordering.
💻 Benchmark Python3 Implementation
class Solution:
def verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
from collections import defaultdict, deque
if not root:
return []
cols = defaultdict(list)
q = deque([(root, 0)]) # (node, column)
while q:
node, c = q.popleft()
cols[c].append(node.val)
if node.left:
q.append((node.left, c - 1))
if node.right:
q.append((node.right, c + 1))
return [cols[c] for c in sorted(cols)]⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n + w log w) where w is the number of distinct columns: the BFS is linear and the final sort is over the columns.
💾 Space Complexity
O(n) for the map and the queue.
⚠️ Interview Pitfalls & Follow-ups
- Using DFS: it does not guarantee top-to-bottom ordering within a column; you would need to sort by depth and then by traversal order.
- Forgetting to sort the columns: the map's key order is insertion order, not left-to-right.
- Using a list indexed by column with an offset: it works, but the range of columns is unknown up front, making a dict safer.
- Appending children in the wrong order: left must be pushed before right so the left-to-right tie-break holds.
⚡
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,请你设计算法计算二叉树的 垂序遍历 序列。对位于 (row, col) 的每个结点而言,其左右子结点分别位于 (row + 1, col − 1) 和 (row + 1, col + 1) 。树的根结点位于 (0, 0) 。二叉树的 垂序遍历 从最左列开始,一直到最右列,按列索引顺序逐列进行遍历。位于同一列的结点,按从上到下的顺序排列。返回所有节点的值的垂序遍历序列。约束:树中节点数目在范围 [1, 1000] 内;0 ≤ Node.val ≤ 1000。
核心要点
- BFS + 按列分组(标准解) :用 BFS 遍历,队列中存 (节点, 列号) 。BFS 保证「从上到下、从左到右」的顺序,因此把节点值追加到对应列的列表即可。
- 为什么用 BFS 而非 DFS :题目要求同列内「从上到下」,BFS 天然满足;DFS 需要额外记录行号再排序。
- 记录列号范围 :维护 min_col 与 max_col ,最后按列号从小到大输出。
- 复杂度 :O(n) 时间、O(n) 空间。
常见陷阱
- 用 DFS :无法保证同列内「从上到下」的顺序,需要额外按行号排序(且行号相同时还要按值排序,见 987 题)。
- 用 defaultdict(list) 但忘记维护列号范围 :无法确定输出的起止列。
- 遍历 sorted(cols) 而非 range(min_col, max_col+1) :中间的空列会被跳过(虽然本题中相邻列之间不会全空,但显式范围更稳妥)。
- 左子节点用 c + 1 、右子节点用 c − 1 :方向反了。
参考实现
from collections import deque, defaultdict
class Solution:
def verticalOrder(self, root: 'TreeNode') -> list[list[int]]:
if not root:
return []
cols = defaultdict(list)
q = deque([(root, 0)])
min_col = max_col = 0
while q:
node, c = q.popleft()
cols[c].append(node.val) # BFS 保证同列内从上到下
if c < min_col:
min_col = c
if c > max_col:
max_col = c
if node.left:
q.append((node.left, c - 1))
if node.right:
q.append((node.right, c + 1))
return [cols[c] for c in range(min_col, max_col + 1)]