KatInterview

Vertical Column Grouping of Array-Represented Binary Trees

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphstrees-graphsbreadth-first-searcharrays

Last updated

Organize the elements of a binary tree into vertical columns using level-order traversal rules on a level-order array input.

Given a binary tree serialized as a list in level-order format (where non-empty nodes are integers and missing nodes are represented as None), compute its vertical column grouping.

We assign geometric coordinates to every node in the tree:

  • The root node is located at column 0 and level 0.
  • If a node is positioned at (col, level), its left child is at (col - 1, level + 1) and its right child is at (col + 1, level + 1).

Your task is to group the nodes by column index and return a list of columns sorted from the left-most column (smallest index) to the right-most column (largest index).

Within each column:

  1. Nodes located at a higher level (smaller level index) appear before nodes at a deeper level.
  2. If two nodes in the same column share the exact same level, their relative order must match their visitation order in a standard left-to-right breadth-first search (BFS).

The input array represents the binary tree in level-order: the 0th element is the root. Subsequent elements correspond to the children of the non-null nodes in the order those nodes were created/visited.

Constraints

  • $0 \le N \le 10^4$, where $N$ is the number of elements in tree.
  • tree[i] is either an integer between $-10^9$ and $10^9$ or None.
  • If tree is empty or tree[0] is None, return [].

Output

Return a list of lists of integers List[List[int]], representing the columns ordered from left to right.

Examples

Example 1

Input: vertical_order_bst([4, 2, 6, 1, 3, 5, 7])

Output: [[1], [2], [4, 3, 5], [6], [7]]

Example 2

Input: vertical_order_bst([1])

Output: [[1]]

Example 3

Input: vertical_order_bst([1, 2, 3, None, None, 4, 5])

Output: [[2], [1, 4], [3], [5]]

Example 4

Input: vertical_order_bst([5, 3, 8, 2, 4, 7, 9, None, None, None, None, 6])

Output: [[2], [3, 6], [5, 4, 7], [8], [9]]

Hints

Hint 1

How does a standard level-order (BFS) traversal process nodes relative to their row level and horizontal position?

Hint 2

Notice that BFS naturally processes nodes level-by-level from top to bottom, and within each level from left to right. Can you use this property to avoid sorting within columns?

Hint 3

Track the minimum and maximum column index visited during traversal so you can construct the final result in $O(N)$ time.