GeeksforGeeks Medium

Top View of Binary Tree

Top View of Binary Tree is a GeeksforGeeks problem (Medium). Imagine standing above a binary tree and looking straight down. Return the values you can see, from left to right.

  • Each node has a horizontal distance from the root: 0 for the root, minus 1 for every step left, plus 1 for every step right.
  • Nodes with the same horizontal distance stand on one vertical line, and only the highest of them is visible from above.
  • If two nodes on one line are equally high, the problem keeps the left one.
  • Return one value per vertical line, leftmost line first.
Constraints
  • 1 <= number of nodes <= 10⁵
  • 1 <= node value <= 10⁵
treebfshash-table
Open on GeeksforGeeks ↗
02

Intuition

Looking down on a tree, a node is hidden whenever another node sits higher on the same vertical line. So the answer is the shallowest node of each line.

You never have to compare depths if nodes arrive shallow-first. Level-order traversal (BFS) does exactly that: all of depth 0, then all of depth 1, left to right inside each level. The first node BFS meets on a line is therefore the visible one, and the whole rule becomes: keep the first value written for each line and ignore the rest.

How to spot this pattern

Questions about what can be seen from one side of a tree (top, bottom, left or right view) all reduce to the same plan: label each node with a coordinate, then keep one node per coordinate. LeetCode has no such problem; the closest is LeetCode 987 (Vertical Order Traversal), which uses the same labels but keeps every node on each line.

03

Approach

Try it first

Before reading on: sketch [1,2,3,null,4,null,null,null,5] and number each vertical line. Which node is visible on the line that holds 3? Then ask which traversal is sure to meet that node before the one hidden beneath it.

1

Pair each node with its line

Put (root, 0) in a queue. Every queued node carries its horizontal distance, so a child's line is worked out once, from its parent's.

2

Keep only the first node on each line

Pop (node, col). If seen has no entry for col, store node.data; otherwise skip it, because a higher node already covers that line. The first arrival is the highest because BFS goes level by level.

3

Queue the children, left first

Add (node.left, col - 1) before (node.right, col + 1), for the children that exist. Queuing the left child first is what makes the left node win when two nodes tie on both depth and line.

4

List the lines from left to right

When the queue is empty, output seen's values by increasing column. std::map and TreeMap keep their keys sorted already; in Python, sort the keys. Recording the smallest and largest column during the BFS also works and skips the sort.

04

Code in Python, C++ and Java

▶1from collections import deque
▶2 
▶3class Solution:
▶4 def topView(self, root):
▶5 if not root:
▶6 return []
▶7 seen = {}
▶8 q = deque([(root, 0)])
▶9 while q:
▶10 node, col = q.popleft()
▶11 if col not in seen:
▶12 seen[col] = node.data
▶13 if node.left:
▶14 q.append((node.left, col - 1))
▶15 if node.right:
▶16 q.append((node.right, col + 1))
▶17 return [seen[c] for c in sorted(seen)]
col -2col -1col 0col 1col 2102030406090100seen[col]queue = [(10, col 0)]
queue(10, 0)root starts in column 0
columns5one visible node each
The shaded lanes are the vertical lines: a left child sits one lane to the left of its parent, a right child one lane to the right. Looking down, only the highest node in a lane is visible, and BFS reaches it before anything below it.
col -2col -1col 0col 1col 2102030406090100seen[col]10pop 10 → seen[0] = 10
node10column 0, depth 0
seen[0]10first write
queued20, 30children, one column over
Column 0 is still empty, so nothing is above 10. It claims the column and will never be replaced. Its children join the queue one column to the left or right.
col -2col -1col 0col 1col 2102030406090100seen[col]2010pop 20 → seen[-1] = 20
node20column -1, depth 1
seen[-1]20first write
queued40, 60children, one column over
Column -1 is still empty, so nothing is above 20. It claims the column and will never be replaced. Its children join the queue one column to the left or right.
col -2col -1col 0col 1col 2102030406090100seen[col]201030pop 30 → seen[1] = 30
node30column 1, depth 1
seen[1]30first write
queued90, 100children, one column over
Column 1 is still empty, so nothing is above 30. It claims the column and will never be replaced. Its children join the queue one column to the left or right.
col -2col -1col 0col 1col 2102030406090100seen[col]40201030pop 40 → seen[-2] = 40
node40column -2, depth 2
seen[-2]40first write
queuednoneleaf
Column -2 is still empty, so nothing is above 40. It claims the column and will never be replaced.
col -2col -1col 0col 1col 2102030406090100seen[col]40201030pop 60 → col 0 taken, skip
node60column 0, depth 2
seen[0]10kept, 60 is hidden
queuednoneleaf
Column 0 already holds 10, which BFS reached on an earlier level. So 10 sits above 60 and hides it. Skip the write.
col -2col -1col 0col 1col 2102030406090100seen[col]40201030pop 90 → col 0 taken, skip
node90column 0, depth 2
seen[0]10kept, 90 is hidden
queuednoneleaf
Column 0 already holds 10, which BFS reached on an earlier level. So 10 sits above 90 and hides it. Skip the write.
col -2col -1col 0col 1col 2102030406090100seen[col]40201030100pop 100 → seen[2] = 100
node100column 2, depth 2
seen[2]100first write
queuednoneleaf
Column 2 is still empty, so nothing is above 100. It claims the column and will never be replaced.
col -2col -1col 0col 1col 2102030406090100top view40201030100queue empty → return [40, 20, 10, 30, 100]
top view[40, 20, 10, 30, 100]columns -2 to 2
visits7each node once
Queue empty. The first write in each lane survived, and it is always that lane's highest node (green). The map was filled in BFS order, not left to right, so the code sorts the column numbers before reading the values.
05

Common pitfalls

Letting later nodes overwrite

✗ Wrong
seen[col] = node.data
✓ Right
if col not in seen:
    seen[col] = node.data

BFS meets deeper nodes later, so overwriting leaves the lowest node on each line. That is the bottom view, not the top view.

First write wins in a DFS without depths

✗ Wrong
def dfs(node, col):
    if node:
        if col not in seen:
            seen[col] = node.data
        dfs(node.left, col - 1)
        dfs(node.right, col + 1)
✓ Right
def dfs(node, col, depth):
    if node:
        if col not in best or depth < best[col][0]:
            best[col] = (depth, node.data)
        dfs(node.left, col - 1, depth + 1)
        dfs(node.right, col + 1, depth + 1)

A recursive preorder finishes the left subtree before starting the right. A deep node on the left can reach a line first and block a higher node from the right side. Store the depth with each entry and let a strictly shallower node replace it; the strict < keeps the left node on a tie, because preorder meets it first.

Reading the map in insertion order

✗ Wrong
return list(seen.values())
✓ Right
return [seen[c] for c in sorted(seen)]

A plain dict, unordered_map or HashMap remembers the order lines were discovered, which follows the BFS levels. The view must run from the leftmost line to the rightmost, so sort by column.

06

Edge cases

Two nodes equally high in one column

Possible deep in a tree when nothing sits above them, for example two nodes four levels down that reach the same column by different paths. The problem keeps the left one; BFS pushes left children before right ones, so the first write is already that one.

07

Complexity

Time
O(n log n)
Space
O(n)
One BFS visit per node. A sorted map costs O(log n) per lookup, and a hash map plus one sort of the columns at the end has the same bound; tracking the smallest and largest column gets it down to O(n). The Python code above sorts the keys once, after the BFS.
08

How the top view differs from its neighbours

Top view, bottom view and vertical order label nodes with the same columns. Only the rule for what a column keeps changes.

ProblemKeeps per columnWrite rule in BFS
Top viewthe highest node (left one on a tie)write only if the column is empty
Bottom viewthe lowest node (later one on a tie)overwrite every time
Vertical order traversalevery node, top to bottomappend to the column's list
09

Top View of Binary Tree FAQ

Can it be done with recursion?

Carry two numbers into each call: the column and the depth. Keep (depth, value) per column and replace it only when a call arrives with a strictly smaller depth. Without the depth check, a deep node from the left subtree can claim a column before a higher node on the right is reached, as the second demo example shows.

Can you walk through an example?

Take root 10 with children 20 and 30, where 20 has children 40 and 60, and 30 has children 90 and 100. The columns from left to right hold 40; 20; 10, 60 and 90; 30; and 100. The highest of each gives the top view 40 20 10 30 100.