KatInterview

Read a Tree Off Column by Column from a Level-Order List

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

Last 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.
  • None stands for an absent child. Absent nodes have no entries for their own children.
  • Trailing None values may be left out; any entry beyond the end of the list counts as None.
  • An empty list is an empty tree. A list whose root is None is 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.