Top View of Binary Tree
The first node visible at each horizontal distance when the tree is seen from the top.
Key concepts at a glance — for those who already know the basics.
Problem Statement
Top View of Binary Tree
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
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].
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.
How to Think
Do a BFS, tracking each node's horizontal distance (HD)
Root starts at HD = 0. Left child: HD − 1. Right child: HD + 1.
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.
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.
Code
Example
Nodes 5 and 6 share HD=0 but node 1 (root) was seen first — they stay hidden.
Top View vs Bottom View
Top View
Record only the first node per HD — shallowest wins.
Bottom View
Always overwrite — deepest (last) wins.
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.