Read a Tree Off Column by Column from a Level-Order List
Trees & GraphsAuto-graded · 23 test casesLast updated
Decode a level-order tree list, assign each node a column, and output values grouped by column with row-then-reading-order tie-breaking.
You are given a binary tree encoded as a level-order list. Produce its values organized into vertical slices.
Positions
Every node has a column and a row:
- The root sits at column 0, row 0.
- A node's left child sits one column to the left (column - 1) and one row down.
- A node's right child sits one column to the right (column + 1) and one row down.
Output
Return a list of lists, one inner list per column that holds at least one node, ordered from the leftmost column to the rightmost.
Inside each column's list:
- Values appear from the shallowest row to the deepest row.
- If several nodes share the same row and the same column, they appear in the order in which they show up in the input list (that is, left to right within that row). Do not break such ties by comparing values.
An empty tree gives [].
Input encoding
tree is the level-order serialization of the tree:
tree[0]is the root.- Following the root, entries are read two at a time: the first is the left child and the second is the right child of the next non-null node, taking non-null nodes in the order they were listed.
Nonestands for an absent child. Absent nodes have no entries for their own children.- Trailing
Nonevalues may be left out; any entry beyond the end of the list counts asNone. - An empty list is an empty tree. A list whose root is
Noneis also an empty tree.
Constraints
- 0 <= number of nodes <= 100
- -100 <= node value <= 100
- Values may repeat.
Examples
Example 1
Input: columns_from_level_order([3, 9, 20, None, None, 15, 7])
Output: [[9], [3, 15], [20], [7]]
Example 2
Input: columns_from_level_order([3, 9, 8, 4, 0, 1, 7])
Output: [[4], [9], [3, 0, 1], [8], [7]]
Example 3
Input: columns_from_level_order([])
Output: []
Hints
Hint 1
Each node only needs a column number. Rows are implied by the order of the input list, so you can avoid storing them.
Hint 2
Parse and traverse at the same time: keep a queue of non-null nodes with their columns and a pointer into the list that advances by one for every entry read, including None. Do not use 2i+1 / 2i+2 indexing.
Hint 3
Level order already lists nodes row by row and left to right within a row, so appending each value to its column's bucket as you read it gives the required ordering with no sorting of values. Finally output the buckets in increasing column order.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The input is a level-order list, so nodes are already listed row by row, and left to right within each row. That is exactly the tie-breaking order the output requires. If we process nodes in input order and append each value to the bucket for its column, every bucket ends up correctly ordered, with no sorting by row or value.
We do not need to build node objects. We decode the list and compute columns in a single pass:
- If the list is empty or the root is
None, return[]. - Put the root value in bucket 0 and enqueue column 0.
- Keep a pointer
istarting at 1. Pop a columncfrom the queue. The next two entries are the left and right children of that node. - For each entry read (advance
ievery time, including forNone), if it is notNone, append it to bucketc - 1(left) orc + 1(right) and enqueue that column. - Return the buckets sorted by column key.
Why it is correct
- Decoding: The list stores child pairs only for non-null nodes, in level order. The queue holds non-null nodes in level order, so the k-th popped node owns the k-th pair of entries. Heap-style indexing would be wrong because children of missing nodes are omitted.
- Each node placed once: Every entry is read exactly once and appended at that moment.
- Order within a column: Values are appended in input order. Rows never decrease along that order, so a column goes top to bottom, and nodes in the same row and column keep their left-to-right order.
- Column order: Sorting the bucket keys gives leftmost to rightmost, and only non-empty columns exist as keys.
Complexity
- Time: O(n + C log C), where C is the number of columns (C <= n), so O(n log n) at worst. Iterating from the minimum to the maximum column instead of sorting gives O(n).
- Space: O(n) for the queue and the buckets.
Reference solution
from collections import deque
from typing import List, Optional
def columns_from_level_order(tree: List[Optional[int]]) -> List[List[int]]:
if not tree or tree[0] is None:
return []
cols = {0: [tree[0]]}
q = deque([0]) # columns of non-null nodes, in level order
i = 1
while q:
col = q.popleft()
for dc in (-1, 1):
if i < len(tree):
v = tree[i]
i += 1
if v is not None:
cols.setdefault(col + dc, []).append(v)
q.append(col + dc)
return [cols[c] for c in sorted(cols)]