Binary Tree · Views

Bottom View of Binary Tree

The last node visible at each horizontal distance when the tree is seen from the bottom.

BFS + HashMapHorizontal DistanceInterview Essential

Key concepts at a glance — for those who already know the basics.

Problem Statement

Bottom View of Binary Tree

Given the root of a binary tree, return the bottom view of the tree — the last node visible at each horizontal distance when seen from below.
Example 1

Input: root = [1, 2, 3, 4, 5, 6, 7]

Output: [4, 2, 6, 3, 7]

HD columns: −2→4, −1→2, 0→6, +1→3, +2→7

Example 2

Input: root = [1, 2, 3, null, 4, null, 5]

Output: [2, 4, 5, 3]

HD columns: −1→2, 0→4, +1→5, +2→3

Constraints

  • The number of nodes in the tree is in the range [0, 100].
  • Each node's value is in the range [-100, 100].
01

The Rule

Last node seen at each horizontal distance from the root

Assign root HD=0. Left child gets HD−1, right child HD+1. For each HD, the deepest node wins — if two nodes share the same HD and depth, the one processed later (right-wards in BFS) wins.

02

How to Think

1

Do a BFS, tracking each node's horizontal distance (HD)

Root starts at HD = 0. Left child: HD − 1. Right child: HD + 1.

2

For every HD, keep overwriting the map with the current node

BFS visits nodes top-to-bottom, so later overwrites = deeper nodes. That's the bottom view.

3

Read the map sorted by HD from min to max

Gives you the bottom view left-to-right as it would appear from underneath the tree.

03

Code

solution.py
from collections import deque
 
def bottom_view(root):
if not root: return []
hd_map =
queue = deque([(root, 0)])
while queue:
node, hd = queue.popleft()
hd_map[hd] = node.val # always overwrite → last = deepest
if node.left: queue.append((node.left, hd - 1))
if node.right: queue.append((node.right, hd + 1))
return [hd_map[k] for k in sorted(hd_map)]
04

Example

HD=−2HD=−1HD=0HD=+1HD=+21234567Bottom View → [4, 2, 6, 3, 7]
Bottom View:[ 4, 2, 6, 3, 7 ](sorted by HD: −2, −1, 0, +1, +2)

Node 5 and Node 6 both land on HD=0. In BFS order, 6 is processed after 5, so 6 overwrites 5 in the map and appears in the result.

05

Dry Run

Node dequeued
HD
hd_map update
Queue after
1 (root)
0
{0:1}
(2,−1), (3,+1)
2
−1
{0:1, −1:2}
(3,+1),(4,−2),(5,0)
3
+1
{…, +1:3}
(4,−2),(5,0),(6,0),(7,+2)
4
−2
{…, −2:4}
(5,0),(6,0),(7,+2)
5
0
{0:5} ← overwrites 1
(6,0),(7,+2)
6
0
{0:6} ← overwrites 5
(7,+2)
7
+2
{…, +2:7}
empty — done ✓
06

Complexity

Time

O(n log n)

BFS visits every node once — O(n). Sorting HD keys adds O(n log n).

Space

O(n)

Queue holds at most widest level. HashMap stores one entry per unique HD.

Ready to see it in action?

Step through the visualizer to watch the algorithm state update live.

Open Visualizer