KatInterview

Group Binary Tree Nodes into Vertical Columns

Trees & GraphsAuto-graded · 21 test cases
MediumAuto-gradedTrees & Graphstrees-graphsbreadth-first-searchbinary-tree

Last updated

Group nodes of a binary tree represented in array heap layout into vertical columns ordered from left to right.

Given a binary tree serialized as a list in heap indexing layout, group its node values by their vertical horizontal coordinates.

Coordinates and Layout Rules

  • The binary tree is represented as an array a using standard heap storage:
    • The root element is at index 0.
    • For a node located at index i, its left child is stored at index 2 * i + 1 and its right child at index 2 * i + 2.
    • Missing nodes are designated by None.
    • If a child index is beyond the bounds of the array, or if a parent node is None, that child does not exist. (Nodes that are unreachable from the root should be ignored.)
  • Horizontal coordinates ($x$-coordinates) are assigned as follows:
    • The root has $x = 0$.
    • A left child has $x_{left} = x_{parent} - 1$.
    • A right child has $x_{right} = x_{parent} + 1$.

Output Requirements

  • Return a list of columns (each column being a list of node values) sorted by $x$-coordinate in strictly ascending order (leftmost column to rightmost column).
  • Within each individual column:
    • Higher nodes (smaller depth) appear before lower nodes (larger depth).
    • If two or more nodes share both the same $x$-coordinate and the same depth (vertical height), order them from left to right according to their standard level-order appearance.

Constraints

  • $0 \le \text{len}(a) \le 10^4$
  • Each node value is an integer or None.
  • Spatial indices follow standard binary heap indexing.

Examples

Example 1

Input: vertical_order_traversal([3, 9, 20, None, None, 15, 7])

Output: [[9], [3, 15], [20], [7]]

Example 2

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

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

Example 3

Input: vertical_order_traversal([1, 2, 3, 4, 5, None, 6, 7, None, None, None, None, 8])

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

Hints

Hint 1

A Breadth-First Search (BFS) naturally processes nodes level-by-level from top to bottom, and within each level, from left to right.

Hint 2

Since BFS processes nodes in the exact order required for tie-breaking within a column, appending a node's value to its corresponding column list upon dequeuing automatically satisfies all sorting criteria.

Hint 3

Track the minimum and maximum horizontal coordinates observed during traversal so that you can gather the resulting columns sequentially without needing an extra key sorting step.