Vertical Order Traversal of a Binary Tree

hard

Given the root of a binary tree, return its vertical order traversal.

Assign each node a position (row, col): the root is (0, 0), and a node at (row, col) has its left child at (row + 1, col - 1) and its right child at (row + 1, col + 1). Group nodes by column from left to right. Within a column, order nodes by row (top to bottom); if two nodes share the same row and column, order them by value (smaller first).

The tree is given in level-order (breadth-first), using null for missing children.

Hints

Assign each node a (row, col): left child (row+1, col-1), right child (row+1, col+1).
Group by column (left to right); within a column order by row.
When two nodes share the same (row, col), break the tie by value — the subtle rule here.

Common doubts

Vertical order keeps every node in a column (not just one), and it sorts same-position nodes by value.
Two nodes at the same (row, col) must be ordered by value regardless of when they're visited, so an explicit value sort is required.
The sort by (col, row, value): O(n log n).

Interview follow-ups

It omits the value tie-break, ordering same-column nodes purely by traversal/level order.
Skip the final left-to-right flattening and return the column-to-values map directly.

Fun facts

  • The value tie-break was added in LeetCode 987 to disambiguate 314's under-specified ordering.
  • Column index is the same 'horizontal distance' used by top and bottom views.

Asked at

AmazonFacebookMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: root = [3, 9, 20, null, null, 15, 7]
Output: [[9], [3, 15], [20], [7]]
Columns -1, 0, 1, 2. Column 0 holds 3 (row 0) then 15 (row 2).
Example 2
Input: root = [1, 2, 3, 4, 5, 6, 7]
Output: [[4], [2], [1, 5, 6], [3], [7]]
In column 0, nodes 5 and 6 share row 2, so they are ordered by value: 5 then 6.
Constraints

- The number of nodes is in the range [0, 1000] - 0 <= Node.val <= 1000

Solve this problem →