Vertical Order Traversal
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Trees.
Vertical Order Traversal
Vertical columns.
Approach 1
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.
⏱ O(N log N)💾 O(N)
Detailed Dry Run
Col -1: [2]. Col 0: [1, 3]. Col 1: [4]. Sorting ensures correct ordering.
Approach 2
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.
⏱ O(N log N)💾 O(N)
Detailed Dry Run
Similar to Level I but uses Queue.
Approach 3
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.
⏱ O(N)💾 O(N)
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]} |
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.