Binary Tree · Views

Top View of Binary Tree

The first node visible at each horizontal distance when the tree is seen from the top.

BFS + HashMapHorizontal DistanceInterview Essential

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

Problem Statement

Top View of Binary Tree

Given the root of a binary tree, return the top view of the tree — the first node visible at each horizontal distance when seen from above.
Example 1

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

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

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

Example 2

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

Output: [1, 2, 3]

Right-skewed tree — HD columns: 0→1, +1→2, +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

First 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, only the shallowest (topmost) node is visible — if an HD column already has an entry, ignore any deeper node in that column.

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, record only the first node you encounter — never overwrite

BFS visits nodes top-to-bottom, so the first node at any HD is the shallowest. That's the top view.

3

Read the map sorted by HD from min to max

Gives you the top view left-to-right as it would appear looking down at the tree from above.

03

Code

solution.py
from collections import deque
 
def top_view(root):
if not root: return []
hd_map =
queue = deque([(root, 0)])
while queue:
node, hd = queue.popleft()
if hd not in hd_map:
hd_map[hd] = node.val
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=+212345/6hidden5/6hidden7Top View = [4, 2, 1, 3, 7]

Nodes 5 and 6 share HD=0 but node 1 (root) was seen first — they stay hidden.

Step
Node
HD
Action
hd_map state
Init
1
0
Write
{0:1}
L2-left
2
−1
Write
{0:1, −1:2}
L2-right
3
+1
Write
{…, +1:3}
L3-LL
4
−2
Write
{…, −2:4}
L3-LR
5
0
Skip
HD=0 exists (node 1)
L3-RL
6
0
Skip
HD=0 exists (node 1)
L3-RR
7
+2
Write
{…, +2:7}
05

Top View vs Bottom View

Top View

if hd not in hd_map:
hd_map[hd] = node.val

Record only the first node per HD — shallowest wins.

Bottom View

# no condition —
hd_map[hd] = node.val

Always overwrite — deepest (last) wins.

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 holds at most n entries.

Ready to see it in action?

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

Open Visualizer