Column-by-Column Readout of a Level-Order Encoded Tree
Trees & GraphsAuto-graded · 22 test casesLast updated
Compute the column-wise readout of a binary tree given as a level-order array, ordering nodes by column, then row, then value.
Column-by-Column Readout of a Level-Order Encoded Tree
You are given a binary tree encoded as a list in level-order (breadth-first) form. Each entry is either an integer node value or None, meaning "no node here". Your task is to report the node values grouped by vertical column.
Encoding
- The first entry is the root. If the list is empty or the first entry is
None, the tree is empty. - Entries are read level by level. Only real (non-
None) nodes have children listed. For each real node, taken in the order they appear level by level, the next unread entry is its left child and the entry after that is its right child. ANonemeans that child is absent, and absent children do not get entries for their own children. - The list may end early. Any child slot beyond the end of the list is treated as absent. Trailing
Nonevalues may appear.
Coordinates
Give each node a position (row, col):
- The root is at
(0, 0). - A node at
(row, col)has its left child at(row + 1, col - 1)and its right child at(row + 1, col + 1).
Output
Return a list of lists of integers, one inner list per occupied column:
- Columns are ordered from the smallest column index to the largest.
- Within a column, nodes are ordered by row, from smallest to largest (top to bottom).
- If several nodes share the same row and column, the one with the smaller value comes first.
- If they also have equal values, all of them still appear (their order among themselves is irrelevant).
If the tree is empty, return an empty list.
Constraints
- The tree has between 0 and 1000 nodes (an empty input is handled by returning
[]). 0 <= value <= 1000for every node.- The solution should run faster than
O(N^2).
Examples
Example 1
Input: column_readout([3, 9, 20, None, None, 15, 7])
Output: [[9], [3, 15], [20], [7]]
Example 2
Input: column_readout([1, 2, 3, 4, 5, 6, 7])
Output: [[4], [2], [1, 5, 6], [3], [7]]
Hints
Hint 1
Assign every node a (row, col) coordinate while you walk the tree level by level; the encoding is already in BFS order, so you can decode it with a single moving index instead of building node objects.
Hint 2
Collect nodes into a dictionary keyed by column, storing (row, value) pairs. Then you only need to sort the column keys and sort each column's pairs.
Hint 3
Sorting each column's pairs as tuples (row, value) automatically handles both the top-to-bottom rule and the smaller-value-first tie-break for nodes sharing a position.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every node needs a coordinate (row, col), and the answer is ordered by column, then row, then value. So the plan is:
- Walk the tree breadth-first, tracking
(value, row, col)for each node. The root is(0, 0); a left child is(row + 1, col - 1)and a right child is(row + 1, col + 1). - Store each node in a dictionary:
col -> list of (row, value). - Sort the column keys. For each column, sort its
(row, value)tuples and output the values.
Decoding the array while walking
The input is in level order, and BFS dequeues real nodes in exactly the same order. So the children of the k-th dequeued node are the next two unread entries of the array. A single pointer next_index advances through the array: the next entry is the left child, the one after is the right child. If an entry is None or the pointer is past the end, that child is skipped. No tree objects are needed.
Why it is correct
- Decoding: the encoding lists children only for real nodes, in level order, which is the order BFS dequeues them, so each child is attached to the correct parent.
- Coordinates: by induction from the root at
(0, 0), each child's position follows from its parent's position. - Ordering: sorting the column keys gives left-to-right order. Sorting
(row, value)tuples gives top-to-bottom order, and among nodes at the same position, the smaller value first. Equal values are both kept since nothing is deduplicated.
Complexity
Let N be the number of nodes.
- Time: O(N log N). BFS is O(N); sorting the column keys and each column's list costs at most O(N log N) overall.
- Space: O(N) for the dictionary, queue and output.
Reference solution
from collections import defaultdict, deque
from typing import List, Optional
def column_readout(tree: List[Optional[int]]) -> List[List[int]]:
if not tree or tree[0] is None:
return []
columns = defaultdict(list)
queue = deque([(tree[0], 0, 0)])
next_index = 1
while queue:
value, row, col = queue.popleft()
columns[col].append((row, value))
if next_index < len(tree):
left_value = tree[next_index]
next_index += 1
if left_value is not None:
queue.append((left_value, row + 1, col - 1))
if next_index < len(tree):
right_value = tree[next_index]
next_index += 1
if right_value is not None:
queue.append((right_value, row + 1, col + 1))
result = []
for col in sorted(columns):
entries = sorted(columns[col])
result.append([value for _, value in entries])
return result