Problem Description
Given the root of a binary tree, return the vertical order traversal of its nodes’ values. Nodes are grouped by their column (vertical) order where the leftmost column comes first and within the same column nodes are ordered from top to bottom. If two nodes share the same position (row and column), they should appear in the order from left to right.
Key Insights
- Use Breadth-First Search (BFS) to traverse the tree level by level.
- Track the column index for each node where root is column 0, left child is column-1, and right child is column+1.
- Group nodes by their column indices using a hash table (or dictionary).
- BFS traversal naturally handles left-to-right ordering within the same level.
- Finally, sort the keys (column indices) to generate results from leftmost column to rightmost column.
Space and Time Complexity
Time Complexity: O(n log n) in the worst-case due to sorting the column indices (n nodes in the worst-case if each node is on a unique column).
Space Complexity: O(n) for storing the node information and the resultant structure.
Solution
The solution uses BFS with a queue that stores nodes along with their corresponding column index. For each visited node, add its value to a dictionary keyed by its column index. When processing children, update the column index appropriately (left child: col-1, right child: col+1). After the traversal, sort the keys of the dictionary and compile the node values in order from smallest to largest column index. This approach guarantees that nodes at the same level will be processed in left-to-right order, matching the required output.