Column-Order Binary Tree Traversal

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement a function vertical_traversal(root: List[Optional[int]]) -> List[List[int]] that groups the values of a binary tree column by column according to 2D grid coordinates.

The input root encodes a binary tree in compact level-order format: root[0] is the root value, and subsequent elements supply (left_child, right_child) pairs for each existing node in breadth-first order. A None entry marks an absent child of an existing parent, and absent nodes do not spawn further child slots in root.

Assign integer grid coordinates (row, col) to every node in the tree as follows:

  • Place the root node at (0, 0).
  • For any parent at (row, col), place its left child at (row + 1, col - 1) and its right child at (row + 1, col + 1).

Return a list of non-empty column lists ordered from the smallest col (leftmost) to the largest col (rightmost). Inside each column list:

  1. Order node values from smallest row (shallowest) to largest row (deepest).
  2. Whenever multiple nodes share identical (row, col) coordinates, list smaller integer values before larger ones.
  3. If multiple nodes at the exact same (row, col) also have identical integer values, include every copy.

Examples

Example 1

Input: root = [25, 4, 12, None, None, 10, 14, 5]
Output: [[4, 5], [25, 10], [12], [14]]

Placing each node on the (row, col) coordinate grid gives: - 25 at (0, 0) - 4 at (1, -1) and 12 at (1, +1) - 4 has two None children; 12 has left child 10 at (2, 0) and right child 14 at (2, +2) - 10 has left child 5 at (3, -1)

Reading columns from -1 through +2 yields [4, 5] for column -1, [25, 10] for column 0 (25 precedes 10 because row = 0 is above row = 2), [12] for column +1, and [14] for column +2.

Example 2

Input: root = [10, 20, 30, 40, 9, 7, 50]
Output: [[40], [20], [10, 7, 9], [30], [50]]

In this complete three-level tree, 9 (the right child of 20) and 7 (the left child of 30) both land at (row = 2, col = 0). Because they occupy the exact same cell, the smaller value 7 appears ahead of 9, making column 0 equal to [10, 7, 9].

Constraints

  • The tree contains between 1 and 1000 nodes inclusive.
  • Every node value val is an integer with 0 <= val <= 1000.
  • Your algorithm must run in strictly sub-quadratic time (faster than O(N^2)).

Step-by-step walkthrough

  1. Understand the grid coordinates and sorting rules

    Imagine drawing the binary tree on a 2D grid of (row, col) coordinates:

    • The root sits at (row = 0, col = 0).
    • Moving to a left child goes one row down and one column left: (row + 1, col - 1).
    • Moving to a right child goes one row down and one column right: (row + 1, col + 1).

    Here is how Example 2 ([10, 20, 30, 40, 9, 7, 50]) lands on that grid:

    col:        -2         -1          0         +1         +2
    row 0:                         10(0,0)
                                  /       \
    row 1:              20(1,-1)             30(1,+1)
                        /      \             /      \
    row 2:    40(2,-2)           9(2,0) 7(2,0)       50(2,+2)
                  |         |          |          |        |
    output:     [40]      [20]     [10, 7, 9]   [30]     [50]
    

    Notice that nodes 9 and 7 take different paths (left -> right versus right -> left), yet both land on the exact same cell (row = 2, col = 0), where 7 must appear before 9.

    Every ordering requirement combines into one clean comparison across all nodes:

    1. Leftmost column to rightmost column (col ascending).
    2. Within the same column, top to bottom (row ascending).
    3. Within the same column and same row, smaller value first (val ascending).

    That means a node's exact position in the final reading order is completely determined by the 3-tuple (col, row, val).

    Also note the input format: root arrives as a compact level-order list (List[Optional[int]]) such as [25, 4, 12, None, None, 10, 14, 5], so our first job is turning that list into linked tree nodes.

  2. Rebuild the tree from the level-order list

    In compact level-order format, values[0] is the root, and after that values arrive in (left_child, right_child) pairs for each real node in top-to-bottom, left-to-right order. Missing children of a real node are written as None, and children of a None are omitted completely.

    Because children of None are omitted, array heap math (2*i + 1 and 2*i + 2) does not work:

    values = [1, None, 2, 3]
    
    Index:     0     1    2  3
              [1]  None  [2] [3]
               |          |
            root=1     right=2 -> its left child is 3 (at index 3, NOT index 5!)
    

    Instead, we keep a FIFO queue (collections.deque, a double-ended queue supporting O(1) pops from the left and appends on the right) of already-created TreeNode parents waiting to receive their two child slots.

    Be careful to test values[idx] is not None rather than if values[idx]:—node values can be 0, and in Python bool(0) is False.

    from typing import List, Optional
    from collections import deque
    
    
    class TreeNode:
        def __init__(self, val: int):
            self.val = val
            self.left: Optional["TreeNode"] = None
            self.right: Optional["TreeNode"] = None
    
    
    def build_tree(values: List[Optional[int]]) -> Optional[TreeNode]:
        """Rebuild a binary tree from a compact level-order list where None marks a missing child."""
        if not values or values[0] is None:
            return None
    
        root = TreeNode(values[0])
        # parents: FIFO queue of already-created TreeNodes waiting for their left/right children
        parents = deque([root])
        idx = 1
    
        while parents and idx < len(values):
            parent = parents.popleft()
    
            # Check `is not None` explicitly because 0 is a valid node value (0 <= val <= 1000).
            if values[idx] is not None:
                parent.left = TreeNode(values[idx])
                parents.append(parent.left)
            idx += 1
    
            if idx < len(values) and values[idx] is not None:
                parent.right = TreeNode(values[idx])
                parents.append(parent.right)
            idx += 1
    
        return root
    
  3. Why scanning cell by cell is too slow

    A literal grid approach would find the column bounds min_col .. max_col and row bounds 0 .. max_row, then loop over every (col, row) cell on that rectangle to gather matching nodes.

    On a skewed tree—say 1,000 nodes all chaining to the left—there are N columns and N rows, creating an N × N grid of 1,000,000 cells even though only 1,000 cells hold a node. Checking every grid cell takes at least O(N^2) work (or O(N^3) if you rescan the tree per cell), violating the sub-quadratic time requirement.

    Flip the question around: instead of asking every grid cell "which nodes landed here?", visit each of the N nodes once and tag it with (col, row, val).

  4. Collect `(col, row, val)` triples with iterative BFS

    We can collect (col, row, val) using Breadth-First Search (BFS)—a traversal that explores the tree level by level using an explicit queue. Using an iterative queue rather than recursive Depth-First Search (DFS) is safer in Python: on a 1,000-node skewed chain, recursion creates 1,000 nested function calls and can hit CPython's default recursion limit (~1,000 frames).

    Note that BFS visit order by itself does not solve same-cell ties: in Example 2 ([10, 20, 30, 40, 9, 7, 50]), BFS visits 9 (from parent 20) before 7 (from parent 30), even though both sit at (row = 2, col = 0) and 7 must come first.

    Sorting our list of (col, row, val) triples fixes columns, rows, and same-cell value ties in one O(N log N) step, because Python compares tuples from left to right.

    def collect_and_sort(tree_root: TreeNode):
        # entries: list of (col, row, val) tuples, e.g. [(-1, 1, 4), (0, 0, 25), (0, 2, 10)]
        entries = []
        # bfs_queue: FIFO queue of (node, row, col) starting with the root at (0, 0)
        bfs_queue = deque([(tree_root, 0, 0)])
    
        while bfs_queue:
            node, row, col = bfs_queue.popleft()
            entries.append((col, row, node.val))
    
            if node.left is not None:
                bfs_queue.append((node.left, row + 1, col - 1))
            if node.right is not None:
                bfs_queue.append((node.right, row + 1, col + 1))
    
        entries.sort()
        return entries
    
  5. Group sorted triples into columns

    Once entries is sorted by (col, row, val), all entries belonging to the same column sit next to each other, already ordered from top row to bottom row and smallest value to largest value within ties.

    Can there be an empty column gap between two occupied columns? Never: every edge changes col by +1 or -1 starting from 0, so a path to column c must step through every integer column between 0 and c. That means we simply start a new inner list each time col changes.

    Initialize current_col = None (rather than 0) so the very first column triggers a new list even when min_col happens to be 0.

    def group_by_column(entries):
        columns_out = []
        current_col = None
    
        for col, row, val in entries:
            # Compare against None / previous int so column 0 is treated as a real column.
            if current_col is None or col != current_col:
                columns_out.append([])
                current_col = col
            columns_out[-1].append(val)
    
        return columns_out
    
  6. Trace Example 1 step by step

    Let's trace root = [25, 4, 12, None, None, 10, 14, 5]:

    Tree with (row, col):
              25 (0, 0)
             /         \
        4 (1, -1)     12 (1, +1)
                      /        \
                 10 (2, 0)    14 (2, +2)
                 /
            5 (3, -1)
    
    1. BFS collects (col, row, val):
       [(0, 0, 25), (-1, 1, 4), (1, 1, 12), (0, 2, 10), (2, 2, 14), (-1, 3, 5)]
    
    2. entries.sort() orders by (col, row, val):
       [(-1, 1, 4), (-1, 3, 5),  (0, 0, 25), (0, 2, 10),  (1, 1, 12),  (2, 2, 14)]
         ------ col = -1 ------   ------ col = 0 -------    col = +1     col = +2
    
    3. Group consecutive equal `col` values:
       [[4, 5], [25, 10], [12], [14]]
    

    In column 0, node 25 (row = 0) comes before node 10 (row = 2) even though 25 > 10, because row (0 < 2) sits ahead of val in (col, row, val).

  7. Complete solution

    Putting tree reconstruction, iterative BFS coordinate tagging, tuple sorting, and column grouping together gives the complete solution:

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    
    
    class TreeNode:
        def __init__(self, val: int):
            self.val = val
            self.left: Optional["TreeNode"] = None
            self.right: Optional["TreeNode"] = None
    
    
    def build_tree(values: List[Optional[int]]) -> Optional[TreeNode]:
        """Rebuild a binary tree from a compact level-order list where None marks a missing child."""
        if not values or values[0] is None:
            return None
    
        root = TreeNode(values[0])
        # parents: FIFO queue of already-created TreeNodes waiting for their left/right children
        parents = deque([root])
        idx = 1
    
        while parents and idx < len(values):
            parent = parents.popleft()
    
            # Check `is not None` explicitly because 0 is a valid node value (0 <= val <= 1000).
            if values[idx] is not None:
                parent.left = TreeNode(values[idx])
                parents.append(parent.left)
            idx += 1
    
            if idx < len(values) and values[idx] is not None:
                parent.right = TreeNode(values[idx])
                parents.append(parent.right)
            idx += 1
    
        return root
    
    
    def vertical_traversal(root: List[Optional[int]]) -> List[List[int]]:
        # Phase 1: Convert the serialized level-order list into linked TreeNode objects.
        tree_root = build_tree(root)
        if tree_root is None:
            return []
    
        # Phase 2: Visit every node iteratively to record its grid coordinates.
        # Iterative BFS avoids hitting Python's ~1000-frame recursion limit on a 1000-node chain.
        # entries: list of (col, row, val) tuples, e.g. [(-1, 1, 4), (0, 0, 25), (0, 2, 10)]
        entries: List[Tuple[int, int, int]] = []
        # bfs_queue: FIFO queue of (node, row, col) starting with the root at (0, 0)
        bfs_queue = deque([(tree_root, 0, 0)])
    
        while bfs_queue:
            node, row, col = bfs_queue.popleft()
            entries.append((col, row, node.val))
    
            if node.left is not None:
                bfs_queue.append((node.left, row + 1, col - 1))
            if node.right is not None:
                bfs_queue.append((node.right, row + 1, col + 1))
    
        # Phase 3: Sort all triples. Python compares tuples element by element:
        # 1) col ascending (leftmost to rightmost),
        # 2) row ascending (top to bottom),
        # 3) val ascending (tie-breaker when two nodes share the exact same cell).
        entries.sort()
    
        # Phase 4: Slice the sorted triples into one inner list per column.
        # Because every edge moves col by +1 or -1, occupied columns form a contiguous range
        # with no empty gaps, so starting a new list whenever `col` changes is exact.
        columns_out: List[List[int]] = []
        current_col: Optional[int] = None
    
        for col, row, val in entries:
            # Compare against None / previous int so column 0 is treated as a real column.
            if current_col is None or col != current_col:
                columns_out.append([])
                current_col = col
            columns_out[-1].append(val)
    
        return columns_out
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture hanging a tree-shaped mobile of numbered ornaments in front of a ruled pegboard. The top ornament hangs at (row = 0, col = 0), every left wire steps one peg down and one peg left (row + 1, col - 1), and every right wire steps one peg down and one peg right (row + 1, col + 1). Reading the column order is like sweeping a vertical laser from the leftmost peg column to the rightmost, reading ornaments from top to bottom inside each column, and breaking ties on the exact same peg by picking the smaller number first.

A naive approach might allocate a 2D rows × cols grid and scan every cell, or group nodes by column during a plain traversal without sorting. Scanning a full 2D grid wastes O(N^2) time when the tree is a long diagonal chain of N nodes because almost every grid cell is empty. Simply appending nodes into column lists during Breadth-First Search (BFS)—a level-by-level traversal using a first-in, first-out queue—also fails whenever two nodes land on the exact same (row, col) peg, because BFS visits them left-to-right by parent position rather than smallest value first.

Instead, we visit each node once, tag it with the 3-element tuple (col, row, val), and rely on lexicographical tuple comparison (comparing tuples slot by slot from left to right) to sort everything in one pass. On [25, 4, 12, None, None, 10, 14, 5], BFS tags the 6 nodes as (0, 0, 25), (-1, 1, 4), (1, 1, 12), (0, 2, 10), (2, 2, 14), and (-1, 3, 5). Sorting those six tuples yields (-1, 1, 4), (-1, 3, 5), (0, 0, 25), (0, 2, 10), (1, 1, 12), (2, 2, 14), and slicing wherever col changes produces [[4, 5], [25, 10], [12], [14]].

Complexity

  • Time: O(N log N), where N is the number of nodes in the tree. Rebuilding the tree from the level-order list touches each entry once in O(N) using a deque (a double-ended queue with O(1) appends and left-pops), the BFS visits each of the N nodes once in O(N), sorting the N tuples takes O(N log N) comparisons, and slicing into columns scans the N sorted tuples once in O(N).
  • Space: O(N). The reconstructed tree, the BFS queue, the entries list of N triples, and the output list of lists each hold at most O(N) items at any time.

Edge cases

  • Single-node tree ([5]): Produces a single column [[5]]; initializing current_col = None ensures column 0 starts a new inner list cleanly.
  • Node value 0 ([0, 10, 20]): Checking values[idx] is not None instead of if values[idx]: preserves 0 as a real node rather than mistaking it for a missing child.
  • Two nodes in the exact same (row, col) cell ([10, 20, 30, 40, 9, 7, 50]): Both 9 and 7 land at (row = 2, col = 0); sorting (col, row, val) places (0, 2, 7) before (0, 2, 9) to output [10, 7, 9], overriding BFS's 9-before-7 visit order.
  • Row order beats value order ([25, 4, 12, None, None, 10, 14, 5]): Node 25 at (0, 0) comes before node 10 at (2, 0), producing [25, 10] in column 0 because row sits ahead of val in the tuple (col, row, val).
  • Duplicate values in the same cell ([1, 2, 2, None, 3, 3]): Both (0, 2, 3) tuples remain in entries, so column 0 outputs [1, 3, 3].
  • Zigzag paths and omitted None children ([1, None, 2, 3]): Right then left returns 3 to column 0 ([[1, 3], [2]]), and build_tree attaches 3 to 2 rather than skipping indices for the missing left child of 1.
  • Skewed chain of 1,000 nodes: Iterative BFS keeps state in heap memory rather than Python's call stack, avoiding RecursionError at N = 1000.

Common mistakes

  • Trusting BFS order alone inside a column: BFS guarantees non-decreasing row order, so shallower nodes always appear first, but two nodes at the same (row, col) arrive in left-to-right parent order instead of ascending val order.
  • Putting row before col in the tuple: Sorting (row, col, val) produces level-by-level order rather than vertical column-by-column order.
  • Sorting each column purely by val: Discarding row puts a small value deep in the tree ahead of a larger root value above it.
  • Indexing the input list with 2*i + 1 and 2*i + 2: Compact serialized binary tree lists omit children of None entries, so heap-index formulas read the wrong slots as soon as any node is missing.
  • Using recursive DFS without checking tree depth: A Depth-First Search (DFS) implemented via recursion adds one stack frame per tree level, which can overflow CPython's ~1,000-frame recursion limit on a 1,000-node chain.

Alternative approaches

  • Hash map keyed by column: Store columns[col].append((row, val)) in a dictionary during BFS, then iterate for col in range(min_col, max_col + 1): and sort each column's (row, val) pairs individually. Worst-case complexity remains O(N log N), though sorting many small column lists often does slightly fewer comparisons than sorting one list of size N.

Follow-up questions

  • What changes if horizontal edge steps can be large arbitrary integers, creating huge gaps between occupied columns? Under unit ±1 horizontal steps, occupied columns are always contiguous with max_col - min_col + 1 <= N, so column span never exceeds N. When arbitrary edge offsets (such as ±10^9) introduce sparse columns, never loop for col in range(min_col, max_col + 1):; instead, either sort (col, row, val) tuples directly and start a new group whenever col != current_col (just as our solution already does!) or bucket into a hash map and iterate over sorted(columns.keys()) in O(N log N) time.
  • How do you guarantee the traversal will not hit Python's call-stack limit on a deeply skewed chain of nodes? Avoid recursion altogether and maintain an explicit work structure in heap memory rather than the call stack (the fixed-depth stack tracking active function frames). Our solution uses iterative BFS with collections.deque([(tree_root, 0, 0)]), and an explicit stack list.pop() for iterative DFS works equally well because entries.sort() orders all (col, row, val) triples identically afterward.
  • How does sorting all coordinate tuples at once compare in time complexity against bucketing nodes by column first? Sorting all N tuples takes O(N log N) time. Bucketing nodes into col lists during BFS gives column order (min_col .. max_col) and ascending row order for free, leaving only same-cell (row, col) ties to sort; in a dense complete tree, middle bottom cells hold Theta(N / sqrt(log N)) nodes whose logarithm is still Theta(log N), keeping comparison sorting O(N log N) worst-case. However, because val (0 .. 1000), row (0 .. N - 1), and col (-(N - 1) .. N - 1) are bounded integers, running three stable counting sort passes (a radix sort that buckets items by integer key in linear time) on val, row, and col achieves O(N + V) = O(N) worst-case time, though Python's built-in Timsort is simpler and faster for N <= 1000.

Follow-up questions

Similar questions

More Bloomberg interview questions

All 47 Bloomberg questions →