#987

Vertical Order Traversal of a Binary Tree

Hard Coordinates + sort

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Give each node a (row, column): the root is (0, 0), a left child is (row + 1, col − 1), a right child is (row + 1, col + 1). Return values column by column from left to right; inside a column sort by row, and break ties by value.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: group nodes by column, sorted by row then value.

Why this works: give each node (col, row); left child col - 1, right col + 1. Sort all triples and group by column.

Example: 3 (9, 20 (15, 7))

col -1: [9], col 0: [3, 15], col 1: [20], col 2: [7]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Ignoring the value tie-break when two nodes share both row and column.

Solve on LeetCode ↗
Complexity
  • Time: O(n log n).
  • Space: O(n).
Topic: Binary Trees
🎬 Episodes 53–60: video coming soon