Column-by-Column Readout of a Binary Tree from Level-Order Input
Trees & GraphsAuto-graded · 23 test casesLast updated
Group binary tree nodes by horizontal column, ordering each column by depth and then by value, with the tree given as a level-order list with nulls.
Column-by-Column Readout of a Binary Tree
You are given a binary tree encoded as a list in level-order, where None marks a missing child. Return the node values grouped by the vertical column each node sits in, from the leftmost column to the rightmost.
Reading the input
The list is read left to right, one level at a time:
level_order[0]is the root.- Each real (non-
None) node, in the order it is discovered, consumes the next two unread entries of the list. The first is its left child and the second is its right child.Nonemeans that child does not exist. - A
Noneentry has no children, so it consumes nothing further. - If the list ends early, all remaining children are absent.
For example, [1, 2, 3, None, 4, None, 5] describes a root 1 with children 2 and 3. Node 2 has no left child and a right child 4. Node 3 has no left child and a right child 5.
Coordinates
Assign each node a position (row, col):
- The root is at
(0, 0). - A left child of a node at
(r, c)is at(r + 1, c - 1). - A right child of a node at
(r, c)is at(r + 1, c + 1).
Output
Return a list of lists. Each inner list holds the values of one column, and the inner lists are ordered by increasing col. Within a column, order the values by:
- Increasing
row(shallower nodes first). - If two nodes share the same
rowand the samecol, increasing node value.
Only columns that contain at least one node appear in the output.
If the tree is empty (the list is empty, or its first entry is None), return an empty list.
Constraints
- The list holds between 0 and about 1000 entries.
- Node values are integers. Duplicate values are allowed.
- The input follows the encoding described above, and trailing
Noneentries may be omitted. - The output must match exactly, including the order within each column.
Examples
Example 1
Input: vertical_slices([3, 9, 20, None, None, 15, 7])
Output: [[9], [3, 15], [20], [7]]
Example 2
Input: vertical_slices([1])
Output: [[1]]
Example 3
Input: vertical_slices([1, 2, 3, 4, 5, 6, 7])
Output: [[4], [2], [1, 5, 6], [3], [7]]
Example 4
Input: vertical_slices([1, 2, 3, None, 4, None, 5])
Output: [[2], [1, 4], [3], [5]]
Hints
Hint 1
Think of each node as a triple (column, row, value). If you sort the triples in that order, the required output ordering falls out directly.
Hint 2
Decode the level-order list with a queue: each node popped takes the next two list entries as its children, and you pass down row + 1 and col -/+ 1 as you push them.
Hint 3
After sorting, walk through the triples and start a new inner list every time the column changes. The traversal order does not matter because the sort decides the final order.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every node gets a coordinate (row, col). The root is (0, 0), a left child shifts the column by -1, a right child shifts it by +1, and both go one row deeper.
- Decode the tree while traversing. Use a queue (BFS). Pop a node, record the triple
(col, row, value), then read the next two entries of the input list as its left and right children. Each non-Nonechild is pushed with its own coordinates. This matches the level-order encoding, where only real nodes consume child slots. - Sort the triples. Python's tuple comparison sorts by
col, thenrow, thenvalue. That is exactly the precedence the problem asks for: column left to right, then top to bottom, then smaller value first for ties at the same cell. - Group by column. Scan the sorted triples and open a new inner list whenever the column differs from the previous one. Append each value to the current list.
- Empty tree. If the list is empty or starts with
None, return[].
Why it is correct
The sort fully determines the output order, so the traversal order (BFS or DFS) cannot affect the result. Since the key is (col, row, value), nodes in the same column end up adjacent, and inside a column they are ordered by row and then value. Grouping consecutive equal columns therefore yields the required lists in increasing column order.
Complexity
- Time: O(N log N). The traversal is O(N) and the sort of N triples dominates.
- Space: O(N) for the triples, the queue and the output.
Reference solution
from collections import deque
from typing import List, Optional
def vertical_slices(level_order: List[Optional[int]]) -> List[List[int]]:
if not level_order or level_order[0] is None:
return []
triples = []
queue = deque([(level_order[0], 0, 0)])
idx = 1
n = len(level_order)
while queue:
val, row, col = queue.popleft()
triples.append((col, row, val))
if idx < n:
left = level_order[idx]
idx += 1
if left is not None:
queue.append((left, row + 1, col - 1))
if idx < n:
right = level_order[idx]
idx += 1
if right is not None:
queue.append((right, row + 1, col + 1))
triples.sort()
result = []
prev_col = None
for col, row, val in triples:
if col != prev_col:
result.append([])
prev_col = col
result[-1].append(val)
return result