Top View of Binary Tree
Values visible from above: for each column, the first node in level order.
Open on GeeksforGeeks ↗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.
Assign each node a horizontal column — left child is c - 1, right is c + 1 — and the top view is the first node seen in each column. BFS is what makes "first" mean "highest", because it visits strictly by depth. Column indexing solves bottom view, vertical order, and top view alike; only the selection rule changes.
Approach
BFS with columns
Queue of (node, col); left −1, right +1. BFS guarantees shallower nodes come first.
First write wins
Only set map[col] if the key is new. DFS would break this — depth order isn't guaranteed.
Sorted columns out
Emit values by ascending column.
Solution & live demo
Common pitfalls
Using DFS instead of BFS
def dfs(node, c, depth):
if c not in seen: seen[c] = node.valq = deque([(root, 0)])
while q:
node, c = q.popleft()
if c not in seen: seen[c] = node.valDFS can reach a deep node in a fresh column before a shallower node in that same column, recording something that isn't actually on top. BFS guarantees the first arrival in any column is the highest one.
Overwriting the column on every visit
seen[c] = node.val
if c not in seen:
seen[c] = node.valLater arrivals in a column are lower in the tree, so overwriting produces the bottom view. First write per column wins.
Returning the values in insertion order
return list(seen.values())
return [seen[c] for c in sorted(seen)]
BFS discovers columns in level order, not left-to-right, so the dictionary's order isn't the visual order. Sorting by column index puts them in the order you'd actually see them.
Edge cases
It IS visible (nothing above it) — first-write logic includes it correctly.
Left-to-right BFS order decides — matches GFG convention.