Vertical Order Traversal
Master this topic with zero to advance depth.
Vertical Order Traversal
Vertical columns.
Level I: DFS with List of Nodes per Column
Intuition
We can perform a DFS and for each node, we pass down its column index. We store nodes in a Map of col -> List<Node>. After traversal, we sort the keys (cols) and then sort each list of nodes by their depth and value.
Logic
- DFS with
(node, col, depth). - Store in
Map<Integer, List<int[]>>(col -> [depth, val]). - Sort.
Detailed Dry Run
Col -1: [2]. Col 0: [1, 3]. Col 1: [4]. Sorting ensures correct ordering.
Level II: BFS with Sorting
Intuition
BFS naturally processes nodes level by level. By adding column information, we can group nodes. However, since multiple nodes can have the same (col, depth), we still need sorting for nodes in the same cell.
Logic
- Queue of
(node, col, depth). - Map of
col -> List of (depth, val). - Sort result lists.
Detailed Dry Run
Similar to Level I but uses Queue.
Level III: Optimal (BFS + Range Tracking)
Intuition
Thought Process
We want to group nodes by their vertical column. Root is col=0. Left child is col-1, Right is col+1.
Since we need to return results from left-to-right, we can track the min and max column indices during BFS. This avoids sorting at the end.
Logic
- Use BFS with a Queue of
(Node, col). - Store nodes in a Map:
Map<Integer, List<Integer>>(col -> list of vals). - Keep track of
minColandmaxCol. - Loop from
minColtomaxColto collect results.
Detailed Dry Run
| Node | Col | Min | Max | Map |
|---|---|---|---|---|
| 3 | 0 | 0 | 0 | {0: [3]} |
| 9 | -1 | -1 | 0 | {0: [3], -1: [9]} |
| 20 | 1 | -1 | 1 | {0: [3], -1: [9], 1: [20]} |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.