Bottom View of Binary Tree
The last node visible at each horizontal distance when the tree is seen from the bottom.
Key concepts at a glance — for those who already know the basics.
Problem Statement
Bottom View of Binary Tree
Input: root = [1, 2, 3, 4, 5, 6, 7]
Output: [4, 2, 6, 3, 7]
HD columns: −2→4, −1→2, 0→6, +1→3, +2→7
Input: root = [1, 2, 3, null, 4, null, 5]
Output: [2, 4, 5, 3]
HD columns: −1→2, 0→4, +1→5, +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
Last 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, the deepest node wins — if two nodes share the same HD and depth, the one processed later (right-wards in BFS) wins.
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, keep overwriting the map with the current node
BFS visits nodes top-to-bottom, so later overwrites = deeper nodes. That's the bottom view.
Read the map sorted by HD from min to max
Gives you the bottom view left-to-right as it would appear from underneath the tree.
Code
Example
Node 5 and Node 6 both land on HD=0. In BFS order, 6 is processed after 5, so 6 overwrites 5 in the map and appears in the result.
Dry Run
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 stores one entry per unique HD.
Ready to see it in action?
Step through the visualizer to watch the algorithm state update live.