KatInterview

Column-Ordered Tree Values From a Level-Order Array

Trees & GraphsAuto-graded · 20 test cases
MediumAuto-gradedTrees & Graphsbinary-treebreadth-first-searchsorting

Last 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-None entry satisfies 0 <= 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.