Vertical Order Traversal solution explained
For vertical order traversal of a binary tree, give the root row 0 and column 0, give each left child column minus one and each right child column plus one, both one row lower, and record a (column, row, value) triple for every node. Sort the triples and group them by column: the sort puts columns left to right, rows top to bottom, and nodes sharing a row and column in increasing value. That runs in O(n log n) time and O(n) space.
By Evin JohnPublished 8 min read
The problem in plain words
Place the root of a binary tree at row 0, column 0. A node at (row, column) has its left child at (row + 1, column - 1) and its right child at (row + 1, column + 1). Return a list of columns, ordered from the leftmost column to the rightmost. Each column lists its values from the top row down. When two or more nodes land on the same row and the same column, list them in ascending order of value.
5 col 0
/ \
3 8 cols -1, +1
/ \ / \
1 9 2 7 cols -2, 0, 0, +2
Answer: [[1], [3], [5, 2, 9], [8], [7]]Nodes 9 and 2 both sit at row 2, column 0. Under this problem's rule they are sorted by value, so column 0 reads 5, 2, 9. A different, often confused problem (sometimes listed as "binary tree vertical order traversal") keeps them in the order a breadth-first search meets them, left to right, which gives 5, 9, 2. Before coding, ask which tie rule applies. It decides the data structure.
What the interviewer wants to see
There is no single clever trick here. The question tests whether you can define a coordinate system, carry it through a traversal, and sort by a compound key without mistakes. A strong candidate states the ordering rules back to the interviewer, including the tie rule, and explains why a depth-first traversal alone does not give top-to-bottom order without a sort. Related questions use the same coordinates:
- Top view. Keep only the first node seen in each column during a BFS.
- Bottom view. Keep the last node seen in each column during a BFS (overwrite as you go).
- Vertical sums. Add values per column instead of listing them; no sort needed.
- Width of the tree in columns. Track the minimum and maximum column.
A naive version: one scan per column
Walk the tree once to compute every node's (row, column). Find the smallest and largest column. Then, for each column in that range, scan all the nodes, keep those in the column, sort them by row and then value, and output their values. It is correct and easy to reason about, but each of the w columns scans all n nodes, so it costs O(n·w) plus the sorting. On a wide, balanced tree w grows with n, and the scans dominate.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def vertical_naive(root):
if root is None:
return []
placed = []
stack = [(root, 0, 0)]
while stack:
node, row, col = stack.pop()
placed.append((row, col, node.val))
if node.left:
stack.append((node.left, row + 1, col - 1))
if node.right:
stack.append((node.right, row + 1, col + 1))
cols = [c for _, c, _ in placed]
result = []
for c in range(min(cols), max(cols) + 1):
here = sorted((r, v) for r, cc, v in placed if cc == c)
result.append([v for _, v in here])
return resultThe standard approach: one sort over triples
Collect a (column, row, value) triple for each node with any traversal. Sorting the triples orders them by column first, then row, then value, which is exactly the required output order, ties included. Then walk the sorted list once and start a new group whenever the column changes. The traversal is O(n), the sort is O(n log n), and the grouping is O(n). Every column between the minimum and maximum is non-empty, since a path to a far column passes through every column in between, so no empty groups appear.
def vertical_traversal(root):
triples = []
def dfs(node, row, col):
if node is None:
return
triples.append((col, row, node.val))
dfs(node.left, row + 1, col - 1)
dfs(node.right, row + 1, col + 1)
dfs(root, 0, 0)
triples.sort()
result = []
last_col = None
for col, _, val in triples:
if col != last_col:
result.append([])
last_col = col
result[-1].append(val)
return resultfunction verticalTraversal(root) {
const triples = [];
const stack = root ? [[root, 0, 0]] : [];
while (stack.length > 0) {
const [node, row, col] = stack.pop();
triples.push([col, row, node.val]);
if (node.left) stack.push([node.left, row + 1, col - 1]);
if (node.right) stack.push([node.right, row + 1, col + 1]);
}
triples.sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]);
const result = [];
let lastCol = null;
for (const [col, , val] of triples) {
if (col !== lastCol) {
result.push([]);
lastCol = col;
}
result[result.length - 1].push(val);
}
return result;
}Calling sort() with no comparator in JavaScript compares values as text, so [10, 9, -2, -1] comes back as [-1, -2, 10, 9], which puts columns in the wrong order. The chained comparator also handles ties at every level of the key.
Follow-up: left-to-right ties with BFS
If nodes at the same position should appear in left-to-right order instead of by value, skip the sort. A breadth-first search visits rows top to bottom and, within a row, left to right, so appending each value to its column's list as you dequeue it already produces the right order. Track the minimum and maximum column to output the lists in order. That version is O(n).
from collections import deque, defaultdict
def vertical_order_bfs(root):
if root is None:
return []
columns = defaultdict(list)
low = high = 0
queue = deque([(root, 0)])
while queue:
node, col = queue.popleft()
columns[col].append(node.val)
low, high = min(low, col), max(high, col)
if node.left:
queue.append((node.left, col - 1))
if node.right:
queue.append((node.right, col + 1))
return [columns[c] for c in range(low, high + 1)]Do not use a depth-first walk for this variant without also tracking rows: DFS reaches a deep left node before a shallow right one in the same column, which breaks the top-to-bottom order.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Scan all nodes for each column | O(n·w + n log n) | O(n) |
| Sort (column, row, value) triples | O(n log n) | O(n) |
| Bucket by column, sort each bucket by (row, value) | O(n log n) in the worst case | O(n) |
| BFS variant (ties left to right) | O(n) | O(n) |
Edge cases
- An empty tree returns an empty list.
- A single node returns one column with one value.
- A tree leaning only left: each node gets its own column, ordered from the deepest node to the root.
- Several nodes at the same row and column, including equal values.
- A zigzag path (left, right, left, right) that keeps returning to the same columns at different rows.
- A deep chain in Python's recursive DFS can hit the recursion limit; the iterative stack in the JavaScript version avoids it.
Mistakes to avoid
- Sorting by column and value only, forgetting the row, which lets a deep small value jump above a shallow large one.
- Applying the wrong tie rule because the two problems have similar names.
- Using DFS order as if it were top to bottom.
- Relying on JavaScript's default sort for numbers.
- Building a map keyed by column and then iterating it in insertion order, which is not left to right.
How to explain it out loud
Fictional example
- Candidate
- Let me confirm the order: columns left to right, then rows top down, and if two nodes share a row and column, smaller value first?
- Interviewer
- Yes.
- Candidate
- Then the output order is exactly the sort order of the tuple column, row, value. I will record that tuple for every node in one traversal and sort once.
- Candidate
- After sorting I group consecutive entries with the same column. That is O(n log n) for the sort. If ties were left to right instead, BFS with a list per column would avoid the sort.
Related walkthroughs
Binary Tree Level Order Traversal is the BFS that the variant builds on. Populating Next Right Pointers organizes the same tree by row instead of column. Sum Root to Leaf Numbers passes state down a DFS the way this problem passes coordinates, and Top K Frequent Elements is another exercise in grouping and ordering by a key.
Where Natively fits
The hardest part of this problem is reading the rules correctly, so practice saying them back. On a Mac or Windows PC, Natively can capture the problem from a screenshot, and its Code hint action can point you toward the ordering rule if you are unsure how ties should be handled. Its transcript of the mock interview makes it easy to see whether you confirmed the ordering before typing. More on the AI interview assistant.
Questions people ask
How do you do a vertical order traversal of a binary tree?
Give the root column 0, left children column minus one and right children column plus one, one row lower. Record (column, row, value) for each node, sort, and group by column.
How are ties handled in vertical order traversal?
In the common version, nodes at the same row and column are sorted by value. A similar problem keeps them in left-to-right BFS order instead, so confirm which rule applies.
What is the time complexity of vertical order traversal?
O(n log n) for the sort of n triples, with O(n) space. The BFS variant with left-to-right ties runs in O(n).
Why not just use a DFS and append to each column?
A depth-first walk can reach a deeper node before a shallower one in the same column, so without the row in a sort key the top-to-bottom order breaks.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
