LeetCode #987 Hard

Vertical Order Traversal

Vertical Order Traversal of a Binary Tree is LeetCode 987 (Hard). Every node gets a position (row, col):

  • The root is at (0, 0).
  • A node at (row, col) has its left child at (row + 1, col - 1) and its right child at (row + 1, col + 1).

Return one list per column, from the leftmost column to the rightmost. Inside a column, list the nodes from top to bottom (increasing row). When two or more nodes share both the same row and the same column, list them in increasing order of value.

The tree has up to 1000 nodes, so collecting every node and sorting is comfortably fast.

Constraints
  • The number of nodes in the tree is in the range [1, 1000].
  • 0 <= Node.val <= 1000
treedfssortinghash-table
Open on LeetCode ↗
02

Intuition

Draw the tree on graph paper and every node gets a cell (row, col). The required output is those nodes read by column, then by row, then by value, so the problem is really a sort in disguise.

Collect (row, value) for each column in one traversal of any kind, then sort each column. The sort alone decides the order, so it does not matter that a DFS may reach a deep node before a shallow one, or which of two nodes in the same cell it meets first.

How to spot this pattern

When an output order is defined by coordinates you can compute per node (column, depth, distance), give every node its coordinate in one traversal and then sort or bucket by the key. Top view, bottom view and diagonal traversal of a binary tree all follow the same plan with a different rule for what each bucket keeps.

03

Approach

Try it first

Before reading on, draw [1,2,3,4,6,5,7] with coordinates and find the cell that holds two nodes. Then decide which sort key puts that column in the right order no matter which traversal you use.

1

Give every node its coordinates

Run dfs(node, row, col) from dfs(root, 0, 0). The left call gets (row + 1, col - 1) and the right call (row + 1, col + 1). BFS works equally well; only the coordinates matter.

2

Bucket by column

Append (row, node.val) to cols[col], a hash map (or sorted map) from column to a list of pairs. Storing the row next to the value is what lets the sort fix the order later.

3

Sort each column and read left to right

Go through the columns in increasing order. Sort each list of pairs: tuples compare by row first and by value on a tie, which is exactly the rule. Keep only the values.

4

Why the order is right

Every node lands in exactly one bucket, so nothing is lost or repeated. Columns are emitted from smallest to largest, and within a column the tuple sort orders by row and then by value, which is the problem's full ordering. The traversal's own visiting order never reaches the output.

04

Code in Python, C++ and Java

▶1from collections import defaultdict
▶2 
▶3 
▶4class Solution:
▶5 def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:
▶6 cols = defaultdict(list) # col -> [(row, val), ...]
▶7 
▶8 def dfs(node, row, col):
▶9 if not node:
▶10 return
▶11 cols[col].append((row, node.val))
▶12 dfs(node.left, row + 1, col - 1)
▶13 dfs(node.right, row + 1, col + 1)
▶14 
▶15 dfs(root, 0, 0)
▶16 res = []
▶17 for col in sorted(cols):
▶18 res.append([val for _, val in sorted(cols[col])])
▶19 return res
col -1col 0col 1col 2r0r1r23920157colsdfs(root, row 0, col 0)
root3(row 0, col 0)
cols{ }col → list of (row, value)
Plan. Every node has a cell on this grid: one row down per level, one column left or right per edge. Record (row, value) under each node's column during one DFS; the sort at the end fixes the order, so the DFS order does not have to be right.
col -1col 0col 1col 2r0r1r23920157colsr03visit 3 → cols[0] gets (r0, 3)
node3row 0, col 0
cols[0][(0,3)]
The root starts at row 0, column 0.
col -1col 0col 1col 2r0r1r23920157colsr19r03visit 9 → cols[-1] gets (r1, 9)
node9row 1, col -1
cols[-1][(1,9)]
9 is the left child of 3 at (0, 0), so it sits at row 1, column -1.
col -1col 0col 1col 2r0r1r23920157colsr19r03r120visit 20 → cols[1] gets (r1, 20)
node20row 1, col 1
cols[1][(1,20)]
20 is the right child of 3 at (0, 0), so it sits at row 1, column 1.
col -1col 0col 1col 2r0r1r23920157colsr19r03r215r120visit 15 → cols[0] gets (r2, 15)
node15row 2, col 0
cols[0][(0,3) (2,15)]
15 is the left child of 20 at (1, 1), so it sits at row 2, column 0. It goes below the 1 pair already in column 0.
col -1col 0col 1col 2r0r1r23920157colsr19r03r215r120r27visit 7 → cols[2] gets (r2, 7)
node7row 2, col 2
cols[2][(2,7)]
7 is the right child of 20 at (1, 1), so it sits at row 2, column 2.
col -1col 0col 1col 2r0r1r23920157sort by row, then valuer19r03r215r120r27sort col 0 → already in order
cols[0][(0,3) (2,15)]sorted by row, then value
values[3, 15]
Rows 0, 2 are already increasing, so the sort leaves column 0 as it is.
col -1col 0col 1col 2r0r1r23920157answerr19r03r215r120r27return [[9],[3,15],[20],[7]]
result[[9],[3,15],[20],[7]]
Read the columns from -1 to 2, keeping only the values: [[9], [3,15], [20], [7]]. Single-node columns needed no sorting at all.
05

Common pitfalls

Keeping traversal order on a tie

✗ Wrong
cols[col].append(node.val)
...
res.append(cols[col])
✓ Right
cols[col].append((row, node.val))
...
res.append([v for _, v in sorted(cols[col])])

In [1,2,3,4,6,5,7], 6 (from the left subtree) and 5 (from the right) both sit at row 2, column 0. Any left-first traversal meets 6 first, but the expected column is [1,5,6].

Sorting by value only

✗ Wrong
sorted(v for _, v in cols[col])
✓ Right
[v for _, v in sorted(cols[col])]

Values decide only ties within the same row. In a column holding the root 9 and a deeper node 2, sorting by value alone puts 2 above 9, which reverses the top-to-bottom order.

Trusting DFS order for rows

✗ Wrong
# DFS visits top to bottom, so rows are already sorted
✓ Right
sort by (row, value) inside each column

DFS finishes the whole left subtree before the right one. In [1,2,3,null,4,null,null,null,6] it reaches 6 at row 3 of column 1 before 3 at row 1 of the same column. BFS does give rows in order, but it still needs the value tie-break.

06

Complexity

Time
O(n log n)
Space
O(n)
In this solution the traversal is O(n). Sorting the columns costs O(k log k) per column of k nodes, at most O(n log n) in total, plus O(w log w) to order w distinct columns. The buckets hold all n pairs.
07

LeetCode 987 vs LeetCode 314 vs the GFG version

Three problems share the name binary tree vertical order traversal. They agree on columns and differ only on ties.

ProblemSame row and columnUsual approach
LeetCode 987, Vertical Order Traversal of a Binary Treesmaller value firstcollect (col, row, value), sort
LeetCode 314, Binary Tree Vertical Order Traversalleft to right, as BFS meets themBFS, append to column lists, no sort
GFG, Vertical Traversal of Binary Treelevel order, like 314BFS with a map from column to list
08

Vertical Order Traversal FAQ

What is the whole method in four lines?
  • Coordinates: root at (0, 0); left child (row + 1, col - 1); right child (row + 1, col + 1).
  • Collect: one DFS or BFS, appending (row, value) to the list for col.
  • Output: columns in increasing order; each column sorted by row, then value.
  • Complexity: O(n log n) time, O(n) space.
Can BFS be used instead of DFS?

Yes. A queue of (node, row, col) visits rows in order, so each column list is already sorted by row. For LeetCode 987 you still have to sort nodes that share a row and column by value; for LeetCode 314 and the GFG version, BFS order alone is the answer.

Why is LeetCode 987 marked Hard?

Not for the algorithm, which is a traversal and a sort. It is the precise ordering rule: the row must be part of the sort for DFS, and nodes in the same cell must be ordered by value rather than by visiting order. Most wrong answers come from one of those two.