KatInterview

Column-by-Column Readout of a Level-Order Encoded Tree

Trees & GraphsAuto-graded · 22 test cases
MediumAuto-gradedTrees & Graphsbinary-treebfshash-map

Last 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. A None means 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 None values 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:

  1. Columns are ordered from the smallest column index to the largest.
  2. Within a column, nodes are ordered by row, from smallest to largest (top to bottom).
  3. If several nodes share the same row and column, the one with the smaller value comes first.
  4. 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 <= 1000 for 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.