Imagine looking at a binary tree from above and dropping vertical lines through each node position. Your task is to collect all the nodes that fall on the same vertical line, from left to right, and within each vertical line, collect nodes from top to bottom.
Given the root of a binary tree, return the vertical order traversal of its nodes' values. This means grouping nodes by their horizontal distance from the root, where:
- Root is at position
0 - Left children are at position
parent - 1 - Right children are at position
parent + 1 - Nodes in the same column should be ordered top to bottom
- If two nodes are at the same position (row and column), order them left to right
Example: For a tree with root value 3, left child 9, and right child 20 (with 20 having children 15 and 7), the vertical order would be [[9], [3, 15], [20], [7]]
Input & Output
Visualization
Time & Space Complexity
Single BFS traversal visits each node exactly once
O(n) for HashMap storage + O(w) for BFS queue where w is maximum width
Constraints
- The number of nodes in the tree is in the range [0, 100]
- Node values are in the range [-100, 100]
- Follow-up: What if nodes at the same position need different ordering rules?