GeeksforGeeks Medium

Top View of Binary Tree

Values visible from above: for each column, the first node in level order.

treebfshash-table
Open on GeeksforGeeks ↗
02

Intuition

💡

Mirror of bottom view: BFS with column indices, but a column is claimed by the FIRST node that reaches it — later (deeper) nodes in that column are hidden underneath.

03

Approach

1

BFS with columns

Queue of (node, col); left −1, right +1. BFS guarantees shallower nodes come first.

2

First write wins

Only set map[col] if the key is new. DFS would break this — depth order isn't guaranteed.

3

Sorted columns out

Emit values by ascending column.

04

Solution & live demo

python
1from collections import deque
2 
3def top_view(root):
4 if not root: return []
5 seen = {}
6 q = deque([(root, 0)])
7 while q:
8 node, c = q.popleft()
9 if c not in seen: # first write per column wins
10 seen[c] = node.val
11 if node.left: q.append((node.left, c - 1))
12 if node.right: q.append((node.right, c + 1))
13 return [seen[c] for c in sorted(seen)]
05

Edge cases

Deep node in an unclaimed column

It IS visible (nothing above it) — first-write logic includes it correctly.

Same level, same column

Left-to-right BFS order decides — matches GFG convention.

06

Complexity

Time
O(n log n)
Space
O(n)
BFS + column sort.