Vertical Column Grouping of Array-Represented Binary Trees
Trees & GraphsAuto-graded · 19 test casesLast updated
Organize the elements of a binary tree into vertical columns using level-order traversal rules on a level-order array input.
Given a binary tree serialized as a list in level-order format (where non-empty nodes are integers and missing nodes are represented as None), compute its vertical column grouping.
We assign geometric coordinates to every node in the tree:
- The root node is located at column
0and level0. - If a node is positioned at
(col, level), its left child is at(col - 1, level + 1)and its right child is at(col + 1, level + 1).
Your task is to group the nodes by column index and return a list of columns sorted from the left-most column (smallest index) to the right-most column (largest index).
Within each column:
- Nodes located at a higher level (smaller
levelindex) appear before nodes at a deeper level. - If two nodes in the same column share the exact same
level, their relative order must match their visitation order in a standard left-to-right breadth-first search (BFS).
The input array represents the binary tree in level-order: the 0th element is the root. Subsequent elements correspond to the children of the non-null nodes in the order those nodes were created/visited.
Constraints
- $0 \le N \le 10^4$, where $N$ is the number of elements in
tree. tree[i]is either an integer between $-10^9$ and $10^9$ orNone.- If
treeis empty ortree[0]isNone, return[].
Output
Return a list of lists of integers List[List[int]], representing the columns ordered from left to right.
Examples
Example 1
Input: vertical_order_bst([4, 2, 6, 1, 3, 5, 7])
Output: [[1], [2], [4, 3, 5], [6], [7]]
Example 2
Input: vertical_order_bst([1])
Output: [[1]]
Example 3
Input: vertical_order_bst([1, 2, 3, None, None, 4, 5])
Output: [[2], [1, 4], [3], [5]]
Example 4
Input: vertical_order_bst([5, 3, 8, 2, 4, 7, 9, None, None, None, None, 6])
Output: [[2], [3, 6], [5, 4, 7], [8], [9]]
Hints
Hint 1
How does a standard level-order (BFS) traversal process nodes relative to their row level and horizontal position?
Hint 2
Notice that BFS naturally processes nodes level-by-level from top to bottom, and within each level from left to right. Can you use this property to avoid sorting within columns?
Hint 3
Track the minimum and maximum column index visited during traversal so you can construct the final result in $O(N)$ time.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task requires grouping binary tree node values by their vertical column indices, ordered from left to right. Within each column, nodes must be sorted by level, breaking ties by left-to-right BFS traversal order.
-
Tree Reconstruction: Since the input is provided as a level-order serialized array of node values (and
Noneplaceholders), we first parse the array into internal node representations. We can maintain a queue of parent node indices and attach non-null child nodes as we iterate through the array. -
Breadth-First Search (BFS) Traversal: A standard left-to-right BFS visits nodes top-to-bottom (increasing
level) and left-to-right within the samelevel. Conveniently, this matches the intra-column ordering rule exactly:- Higher levels are processed before lower levels.
- Nodes at the same level are processed in left-to-right order.
Therefore, running BFS with each node's column coordinate eliminates the need for sorting values within a column. We simply append values to a list mapped to
col. -
Output Formation: During BFS, we keep track of the minimum and maximum column indices reached (
min_colandmax_col). Because tree branches step left (col - 1) and right (col + 1), the columns span a contiguous range frommin_coltomax_col. Iterating frommin_coltomax_colproduces the finalized result in $O(N)$ total time.
Complexity
- Time Complexity: $\mathcal{O}(N)$, where $N$ is the number of nodes in the tree. We parse the input array once and visit each node once during the queue-based traversal. Appending to column lists takes $\mathcal{O}(1)$ time per node.
- Space Complexity: $\mathcal{O}(N)$ to store the node representations, the BFS queue, and the dynamic column mapping.
from collections import defaultdict, deque
from typing import List, Optional
def vertical_order_bst(tree: List[Optional[int]]) -> List[List[int]]:
if not tree or tree[0] is None:
return []
# Reconstruct the tree structure using node indices
# nodes list stores [value, left_child_index, right_child_index]
nodes = [[tree[0], None, None]]
pending = deque([0])
cursor = 1
while pending and cursor < len(tree):
parent = pending.popleft()
for side in (1, 2):
if cursor >= len(tree):
break
value = tree[cursor]
cursor += 1
if value is not None:
child = len(nodes)
nodes.append([value, None, None])
nodes[parent][side] = child
pending.append(child)
# Perform BFS to collect column values in proper order
columns = defaultdict(list)
traversal = deque([(0, 0, 0)]) # (node_index, col, level)
min_col = max_col = 0
while traversal:
index, col, level = traversal.popleft()
value, left, right = nodes[index]
columns[col].append(value)
min_col = min(min_col, col)
max_col = max(max_col, col)
if left is not None:
traversal.append((left, col - 1, level + 1))
if right is not None:
traversal.append((right, col + 1, level + 1))
return [columns[col] for col in range(min_col, max_col + 1)]