Top View of Binary Tree

medium

Given the root of a binary tree, return its top view — the set of nodes visible when the tree is viewed from directly above, ordered from left to right.

Assign each node a horizontal distance: the root is 0, a left child is one less than its parent, a right child one more. For each horizontal distance, the visible node is the topmost one (closest to the root). If two nodes share a horizontal distance at the same depth, the one reached earlier in a top-down, left-to-right sweep is taken.

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

Hints

Assign each node a horizontal distance: root 0, left child -1, right child +1.
The visible node in each column is the topmost — smallest depth.
A level-order BFS visits top-down, so the first node seen per horizontal distance is the one you keep.

Common doubts

BFS processes nodes in nondecreasing depth, so the first node dequeued at a horizontal distance is the shallowest — the top of that column.
Yes, but you must track depth and keep the smallest-depth node per column, since DFS can reach a deep node before a shallow one.
Columns are keyed by horizontal distance, which you must emit left-to-right (most negative to most positive).

Interview follow-ups

Keep the last node seen per horizontal distance instead of the first (in BFS), or the deepest in DFS.
Vertical order groups all nodes per column (not just the top one), ordered by depth then value.

Fun facts

  • Top and bottom views differ by a single word: 'first' versus 'last' node per column in BFS.
  • Horizontal distance is the x-coordinate you'd use to actually draw the tree on paper.

Asked at

AmazonMicrosoftFlipkart
Frequently Sometimes Occasionally
Example 1
Input: root = [1, 2, 3, null, 4, 5, 6]
Output: [2, 1, 3, 6]
Columns by horizontal distance: -1 -> 2, 0 -> 1 (root), 1 -> 3, 2 -> 6.
Example 2
Input: root = [1, 2, 3]
Output: [2, 1, 3]
Left child at hd -1, root at hd 0, right child at hd 1.
Constraints

- The number of nodes is in the range [0, 10^4] - 1 <= Node.val <= 10^5

Solve this problem →