Column-Ordered Tree Values From a Level-Order Array
Trees & GraphsAuto-graded · 20 test casesLast updated
Bucket level-order tree nodes by column, then sort each column by depth and value to produce the grouped output.
You are given a binary tree encoded as a level-order list. values[0] is the root. From there, the array lists nodes breadth-first, two slots per real node: its left child, then its right child. None in a slot means that child is absent, and a missing child contributes no slots of its own. Extra trailing None entries may appear, or the array may simply stop early once no more children exist.
Assign each node a coordinate pair. The root sits at row 0, column 0. For a node at row r, column c, its left child (if present) goes to row r + 1, column c - 1, and its right child goes to row r + 1, column c + 1.
Return a list of lists. There is one inner list per column that contains at least one node, and the inner lists appear in ascending column order (leftmost column first). Inside a given column, nodes are listed top to bottom by row. If two nodes in the same column also share the same row, list the smaller value first, and include both values.
If the array is empty or its root slot is None, return an empty list.
Constraints
1 <= len(values) <= 2000- Each non-
Noneentry satisfies0 <= value <= 1000 - The encoding is always a valid level-order serialization (missing children consume a slot but never any slots below)
- Duplicate values may appear, including within the same row and column
Examples
Example 1
Input: columns_by_height([3, 9, 20, None, None, 15, 7])
Output: [[9], [3, 15], [20], [7]]
Example 2
Input: columns_by_height([1, 2, 3, 4, 5, 6, 7])
Output: [[4], [2], [1, 5, 6], [3], [7]]
Hints
Hint 1
Walk the array with a queue: each real node you dequeue owns the next two array slots as its left and right children.
Hint 2
Track (row, col) as you go, and store each node's (row, value) pair in a dictionary keyed by column.
Hint 3
Sort column keys ascending; inside a column sort the (row, value) tuples — that gives depth order with the value tie-break for free.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Give every node a (row, col) coordinate: the root is (0, 0), a left child moves to (row + 1, col - 1), and a right child moves to (row + 1, col + 1).
The array is already in breadth-first order, so you do not need to build tree objects. Use a queue of (row, col, val) and a pointer index starting at 1. When you pop a node, the next two array slots are its left and right children; read them in that order, advance the pointer for each slot consumed, and enqueue the ones that are not None. Each enqueued child gets row + 1 and the appropriate column. A None slot still advances the pointer but enqueues nothing, which matches the serialization rule that absent children have no slots beneath them. If the pointer passes the end of the array, the remaining children are simply absent.
Store each node's (row, val) pair in a dictionary keyed by column. Then visit the column keys in ascending order. Inside each column, sort the pairs as tuples: Python compares row first, then val, which is exactly the required ordering — shallower nodes earlier, and ties at the same row resolved by smaller value first.
Why It's Correct
Breadth-first order matches the array layout exactly, so the two slots read after popping a node really are that node's children, and each child receives the correct row and column. Sorting the column keys ascending produces left-to-right output. Sorting the (row, val) tuples inside a column orders by depth and then by value, covering the tie-break rule. Nothing is dropped: every non-None node is enqueued exactly once and appended once.
Note that breadth-first order alone is not enough for the value tie-break — within a row it emits nodes by tree position, not by value — so the final sort is essential.
Complexity
- Time: O(N log N), where N is the array length. The traversal is O(N); sorting column keys and each column's bucket is bounded by O(N log N).
- Space: O(N) for the dictionary, the queue (at most one level wide), and the output.
Reference Solution
from collections import defaultdict, deque
from typing import List, Optional
def columns_by_height(values: List[Optional[int]]) -> List[List[int]]:
if not values or values[0] is None:
return []
buckets = defaultdict(list) # col -> list of (row, val)
queue = deque([(0, 0, values[0])]) # (row, col, val)
index = 1 # next unread child slot
while queue:
row, col, val = queue.popleft()
buckets[col].append((row, val))
for child_col in (col - 1, col + 1):
if index < len(values):
child = values[index]
index += 1
if child is not None:
queue.append((row + 1, child_col, child))
result = []
for col in sorted(buckets):
result.append([val for row, val in sorted(buckets[col])])
return result