Group Binary Tree Nodes into Vertical Columns
Trees & GraphsAuto-graded · 21 test casesLast updated
Group nodes of a binary tree represented in array heap layout into vertical columns ordered from left to right.
Given a binary tree serialized as a list in heap indexing layout, group its node values by their vertical horizontal coordinates.
Coordinates and Layout Rules
- The binary tree is represented as an array
ausing standard heap storage:- The root element is at index
0. - For a node located at index
i, its left child is stored at index2 * i + 1and its right child at index2 * i + 2. - Missing nodes are designated by
None. - If a child index is beyond the bounds of the array, or if a parent node is
None, that child does not exist. (Nodes that are unreachable from the root should be ignored.)
- The root element is at index
- Horizontal coordinates ($x$-coordinates) are assigned as follows:
- The root has $x = 0$.
- A left child has $x_{left} = x_{parent} - 1$.
- A right child has $x_{right} = x_{parent} + 1$.
Output Requirements
- Return a list of columns (each column being a list of node values) sorted by $x$-coordinate in strictly ascending order (leftmost column to rightmost column).
- Within each individual column:
- Higher nodes (smaller depth) appear before lower nodes (larger depth).
- If two or more nodes share both the same $x$-coordinate and the same depth (vertical height), order them from left to right according to their standard level-order appearance.
Constraints
- $0 \le \text{len}(a) \le 10^4$
- Each node value is an integer or
None. - Spatial indices follow standard binary heap indexing.
Examples
Example 1
Input: vertical_order_traversal([3, 9, 20, None, None, 15, 7])
Output: [[9], [3, 15], [20], [7]]
Example 2
Input: vertical_order_traversal([1, 2, 3, 4, 5, 6, 7])
Output: [[4], [2], [1, 5, 6], [3], [7]]
Example 3
Input: vertical_order_traversal([1, 2, 3, 4, 5, None, 6, 7, None, None, None, None, 8])
Output: [[7], [4], [2], [1, 5], [3], [6]]
Hints
Hint 1
A Breadth-First Search (BFS) naturally processes nodes level-by-level from top to bottom, and within each level, from left to right.
Hint 2
Since BFS processes nodes in the exact order required for tie-breaking within a column, appending a node's value to its corresponding column list upon dequeuing automatically satisfies all sorting criteria.
Hint 3
Track the minimum and maximum horizontal coordinates observed during traversal so that you can gather the resulting columns sequentially without needing an extra key sorting step.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To group the tree nodes vertically in left-to-right order:
- Coordinate Assignment: The root starts at coordinate $x = 0$. Going to a left child decrements $x$ by 1, and going to a right child increments $x$ by 1.
- Traversal Strategy: Using a Breadth-First Search (BFS) allows us to explore nodes by increasing depth (top-to-bottom) and left-to-right across each level.
- Ordering Guarantee: Because BFS visits nodes level by level, dequeuing a node directly provides the exact sequence required inside each column list (depth first, then left-to-right order). No sorting step is needed within each column.
- Range Collection: By tracking the minimum ($min_x$) and maximum ($max_x$) column coordinates seen, we can collect the output lists by iterating through $x \in [min_x, max_x]$.
Complexity Analysis
- Time Complexity: $\mathcal{O}(N)$ where $N$ is the number of valid (reachable) nodes in the tree. Every reachable node is pushed and popped from the queue exactly once. Constructing the output takes $\mathcal{O}(W)$ where $W$ is the total number of columns ($W \le N$).
- Space Complexity: $\mathcal{O}(N)$ to maintain the queue frontier and the hash map storing column nodes.
Python Reference Solution
from collections import defaultdict, deque
from typing import List, Optional
def vertical_order_traversal(a: List[Optional[int]]) -> List[List[int]]:
if not a or a[0] is None:
return []
column_map = defaultdict(list)
queue = deque([(0, 0)]) # tuple of (array index, x-coordinate)
min_x = 0
max_x = 0
while queue:
idx, x = queue.popleft()
val = a[idx]
column_map[x].append(val)
min_x = min(min_x, x)
max_x = max(max_x, x)
left_idx = 2 * idx + 1
right_idx = 2 * idx + 2
if left_idx < len(a) and a[left_idx] is not None:
queue.append((left_idx, x - 1))
if right_idx < len(a) and a[right_idx] is not None:
queue.append((right_idx, x + 1))
return [column_map[x] for x in range(min_x, max_x + 1)]