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.
- 1 <= number of nodes <= 10⁵
- 1 <= node value <= 10⁵
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.
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.
Approach
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.
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.
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.
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.
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.
Code in Python, C++ and Java
Common pitfalls
Letting later nodes overwrite
seen[col] = node.data
if col not in seen:
seen[col] = node.dataBFS 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
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)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
return list(seen.values())
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.
Edge cases
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.
Complexity
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.
| Problem | Keeps per column | Write rule in BFS |
|---|---|---|
| Top view | the highest node (left one on a tie) | write only if the column is empty |
| Bottom view | the lowest node (later one on a tie) | overwrite every time |
| Vertical order traversal | every node, top to bottom | append to the column's list |
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.