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:
- Order node values from smallest
row(shallowest) to largestrow(deepest). - Whenever multiple nodes share identical
(row, col)coordinates, list smaller integer values before larger ones. - 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
1and1000nodes inclusive. - Every node value
valis an integer with0 <= val <= 1000. - Your algorithm must run in strictly sub-quadratic time (faster than
O(N^2)).
Step-by-step walkthrough
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
9and7take different paths (left -> rightversusright -> left), yet both land on the exact same cell(row = 2, col = 0), where7must appear before9.Every ordering requirement combines into one clean comparison across all nodes:
- Leftmost column to rightmost column (
colascending). - Within the same column, top to bottom (
rowascending). - Within the same column and same row, smaller value first (
valascending).
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:
rootarrives 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.- The root sits at
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 asNone, and children of aNoneare omitted completely.Because children of
Noneare omitted, array heap math (2*i + 1and2*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-createdTreeNodeparents waiting to receive their two child slots.Be careful to test
values[idx] is not Nonerather thanif values[idx]:—node values can be0, and in Pythonbool(0)isFalse.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 rootWhy scanning cell by cell is too slow
A literal grid approach would find the column bounds
min_col .. max_coland row bounds0 .. 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
Ncolumns andNrows, creating anN × Ngrid of 1,000,000 cells even though only 1,000 cells hold a node. Checking every grid cell takes at leastO(N^2)work (orO(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
Nnodes once and tag it with(col, row, val).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 visits9(from parent20) before7(from parent30), even though both sit at(row = 2, col = 0)and7must come first.Sorting our list of
(col, row, val)triples fixes columns, rows, and same-cell value ties in oneO(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 entriesGroup sorted triples into columns
Once
entriesis 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
colby+1or-1starting from0, so a path to columncmust step through every integer column between0andc. That means we simply start a new inner list each timecolchanges.Initialize
current_col = None(rather than0) so the very first column triggers a new list even whenmin_colhappens to be0.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_outTrace 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, node25(row = 0) comes before node10(row = 2) even though25 > 10, becauserow(0 < 2) sits ahead ofvalin(col, row, val).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), whereNis the number of nodes in the tree. Rebuilding the tree from the level-order list touches each entry once inO(N)using a deque (a double-ended queue withO(1)appends and left-pops), the BFS visits each of theNnodes once inO(N), sorting theNtuples takesO(N log N)comparisons, and slicing into columns scans theNsorted tuples once inO(N). - Space:
O(N). The reconstructed tree, the BFS queue, theentrieslist ofNtriples, and the output list of lists each hold at mostO(N)items at any time.
Edge cases
- Single-node tree (
[5]): Produces a single column[[5]]; initializingcurrent_col = Noneensures column0starts a new inner list cleanly. - Node value
0([0, 10, 20]): Checkingvalues[idx] is not Noneinstead ofif values[idx]:preserves0as 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]): Both9and7land at(row = 2, col = 0); sorting(col, row, val)places(0, 2, 7)before(0, 2, 9)to output[10, 7, 9], overriding BFS's9-before-7visit order. - Row order beats value order (
[25, 4, 12, None, None, 10, 14, 5]): Node25at(0, 0)comes before node10at(2, 0), producing[25, 10]in column0becauserowsits ahead ofvalin the tuple(col, row, val). - Duplicate values in the same cell (
[1, 2, 2, None, 3, 3]): Both(0, 2, 3)tuples remain inentries, so column0outputs[1, 3, 3]. - Zigzag paths and omitted
Nonechildren ([1, None, 2, 3]): Right then left returns3to column0([[1, 3], [2]]), andbuild_treeattaches3to2rather than skipping indices for the missing left child of1. - Skewed chain of 1,000 nodes: Iterative BFS keeps state in heap memory rather than Python's call stack, avoiding
RecursionErroratN = 1000.
Common mistakes
- Trusting BFS order alone inside a column: BFS guarantees non-decreasing
roworder, so shallower nodes always appear first, but two nodes at the same(row, col)arrive in left-to-right parent order instead of ascendingvalorder. - Putting
rowbeforecolin the tuple: Sorting(row, col, val)produces level-by-level order rather than vertical column-by-column order. - Sorting each column purely by
val: Discardingrowputs a small value deep in the tree ahead of a larger root value above it. - Indexing the input list with
2*i + 1and2*i + 2: Compact serialized binary tree lists omit children ofNoneentries, 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 iteratefor col in range(min_col, max_col + 1):and sort each column's(row, val)pairs individually. Worst-case complexity remainsO(N log N), though sorting many small column lists often does slightly fewer comparisons than sorting one list of sizeN.
Follow-up questions
- What changes if horizontal edge steps can be large arbitrary integers, creating huge gaps between occupied columns? Under unit
±1horizontal steps, occupied columns are always contiguous withmax_col - min_col + 1 <= N, so column span never exceedsN. When arbitrary edge offsets (such as±10^9) introduce sparse columns, never loopfor col in range(min_col, max_col + 1):; instead, either sort(col, row, val)tuples directly and start a new group whenevercol != current_col(just as our solution already does!) or bucket into a hash map and iterate oversorted(columns.keys())inO(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 stacklist.pop()for iterative DFS works equally well becauseentries.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
Ntuples takesO(N log N)time. Bucketing nodes intocollists during BFS gives column order (min_col .. max_col) and ascendingroworder for free, leaving only same-cell(row, col)ties to sort; in a dense complete tree, middle bottom cells holdTheta(N / sqrt(log N))nodes whose logarithm is stillTheta(log N), keeping comparison sortingO(N log N)worst-case. However, becauseval(0 .. 1000),row(0 .. N - 1), andcol(-(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) onval,row, andcolachievesO(N + V)=O(N)worst-case time, though Python's built-in Timsort is simpler and faster forN <= 1000.
Follow-up questions
- What changes if horizontal edge steps can be large arbitrary integers, creating huge gaps between occupied columns?
- How do you guarantee the traversal will not hit Python's call-stack limit on a deeply skewed chain of nodes?
- How does sorting all coordinate tuples at once compare in time complexity against bucketing nodes by column first?
Similar questions
- Sum Forward-Order Digit Lists
- Equalize Letter Counts by One Deletion
- Minimum Conference Rooms and Postfix Evaluator
- Directed Friend Requests Under Age Bounds
- Island Area Frequency Queries
- Dynamic Multiset Top-K Frequency Tracker
More Bloomberg interview questions
- Count Islands in a Grid Medium
- Check Balanced Delimiter Nesting Medium
- Minimum Substitutions to Form an Anagram Medium Pro
- Enumerate Binary Strings From Wildcard Pattern Medium Pro
- Complete Concrete Subclasses in an Abstract Command Hierarchy Medium Pro
- Parse Clickstream URLs and Tracking Parameters in PostgreSQL Medium Pro
- Software Project Reflection and Technical Leadership Prompts Medium Pro
- Directed Friend Requests Under Age Bounds Medium Pro
- Leading Full-Cycle Client Software Delivery Hard Pro
- Low-Latency Streaming VWAP Market Data Engine Medium Pro