Bottom View of Binary Tree

medium

Given the root of a binary tree, return its bottom view — the set of nodes visible when the tree is viewed from directly below, 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 lowest one (farthest from the root). If two nodes share a horizontal distance at the same depth, the one reached later 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 lowest — greatest depth.
A level-order BFS visits top-down, so overwriting each column leaves the last (lowest) node.

Common doubts

Only one line: instead of recording a column only when it's first seen, you overwrite it every time so the last node wins.
BFS visits nodes in nondecreasing depth, so the final write to a column comes from its deepest node.
The node dequeued later — the more-right one — overwrites, so it's the one shown.

Interview follow-ups

Keep the first node seen per horizontal distance instead of the last.
Vertical order lists every node per column (ordered by depth then value); bottom view keeps only the lowest.

Fun facts

  • Top and bottom views are the same algorithm differing by 'first' vs 'last' node per column.
  • Horizontal distance is exactly the x-coordinate you'd use to plot the tree on graph paper.

Asked at

AmazonFlipkartMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: root = [20, 8, 22, 5, 3, 4, 25]
Output: [5, 8, 4, 22, 25]
Columns by horizontal distance: -2 -> 5, -1 -> 8, 0 -> 4 (lowest at column 0), 1 -> 22, 2 -> 25.
Example 2
Input: root = [1, 2, 3]
Output: [2, 1, 3]
Each of the three nodes is alone in its column.
Constraints

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

Solve this problem →