Top View of a Binary Tree
Problem and examples
| Input Tree | Top View Output | Description |
|---|---|---|
| [1, 2, 3, 4, 5, null, 6] | [4, 2, 1, 3, 6] | Standard tree with multiple levels; leftmost and rightmost nodes at each level appear in top view |
| [1] | [1] | Single node tree; root itself is the top view |
| [] | [] | Empty tree with no nodes returns an empty top view |
| [1, 2, null, 3, null, 4] | [4, 3, 2, 1] | Left-skewed tree; only the leftmost path visible in top view |
| [1, null, 2, null, 3, null, 4] | [1, 2, 3, 4] | Right-skewed tree; every node appears in top view due to unique horizontal distances |
| [1, 2, 3, 4, null, null, 5, 6] | [6, 4, 2, 1, 3, 5] | Complex tree with deep left and right subtrees; top view includes the outermost nodes |
Explore Top View of a Binary Tree - Iterative
Load an example or enter your own input. Use the player controls to follow each change.
Understanding the Problem
The Top View of a binary tree refers to the set of nodes visible when we look at the tree from the top. For each vertical column (based on horizontal distance from the root), we should see only the topmost node — the one that appears first in a top-down traversal.
We’ll solve this using a level-order traversal (BFS) approach, and for each horizontal distance (HD), we record the first node we encounter. This way, we capture the top view from left to right.
Step-by-Step Solution with Example
step 1: Visualize the Tree
Consider the binary tree:
1
/ 2 3
/ 4 5 6
Here, node 1 is the root. Node 2 is on the left, node 3 is on the right. Node 4 is the right child of 2, and nodes 5 and 6 are the children of 3.
step 2: Define Horizontal Distance
Assign a horizontal distance (HD) to each node:
- Root (1) has HD = 0
- Left child decreases HD by 1
- Right child increases HD by 1
So we get:
- Node 1: HD = 0
- Node 2: HD = -1
- Node 3: HD = +1
- Node 4: HD = 0
- Node 5: HD = 0
- Node 6: HD = +2
step 3: Perform Level-Order Traversal
Use a queue for BFS. Track both node and its HD. Maintain a map where key = HD and value = first node seen at that HD.
Processing in BFS order (top to bottom, left to right):
- Visit node 1 (HD=0) → not in map → add
- Visit node 2 (HD=-1) → not in map → add
- Visit node 3 (HD=1) → not in map → add
- Visit node 4 (HD=0) → already in map → skip
- Visit node 5 (HD=0) → already in map → skip
- Visit node 6 (HD=2) → not in map → add
step 4: Extract and Sort Results
The map now has nodes at each horizontal distance:
- HD = -1 → Node 2
- HD = 0 → Node 1
- HD = 1 → Node 3
- HD = 2 → Node 6
Sort keys: [-1, 0, 1, 2], then print values in that order: [2, 1, 3, 6]
Edge Cases
Empty Tree
If the tree is empty (root = null), then the top view is simply an empty list.
Single Node Tree
If the tree has only one node (the root), then the top view contains just that one node.
Left-Skewed Tree
Each node only has a left child. Every node will have a unique HD (all negative) and will be visible from the top.
Right-Skewed Tree
Each node only has a right child. Each node gets a unique positive HD and will appear in the top view.
Overlapping Nodes at Same HD
In trees where multiple nodes share the same HD, only the first node encountered in level-order traversal is taken for the top view. This ensures higher nodes (closer to root) are prioritized.
Finally
The top view of a binary tree helps us understand its vertical structure from above. By tracking horizontal distances during a BFS traversal, we efficiently extract the topmost visible node at each vertical level. Always sort the HDs before output to ensure left-to-right ordering.
This method ensures correctness for all types of binary trees — from skewed to balanced and general trees with complex structures.
- If the tree is empty, return an empty result.
- Initialize a
queueand enqueue a tuple containing the root node and its horizontal distance (0). - Initialize an empty map (or dictionary) to store the first node encountered at each horizontal distance.
- While the queue is not empty, dequeue a tuple (
node,hd). - If the horizontal distance
hdis not present in the map, record the node's value for thathd. - Enqueue the left child with horizontal distance
hd - 1and the right child withhd + 1(if they exist). - After processing all nodes, sort the keys of the map and output the corresponding node values as the top view.
Implementation and efficiency
C implementation
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("Hello, World from C!\n");
return 0;
}C++ implementation
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World from C++!" << endl;
return 0;
}Python implementation
def main():
print("Hello, World from Python!")
if __name__ == "__main__":
main()Java implementation
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World from Java!");
}
}JavaScript implementation
function main() {
console.log("Hello, World from JavaScript!");
}
main();Go implementation
package main
import "fmt"
func main() {
fmt.Println("Hello, World from Go!")
}Rust implementation
fn main() {
println!("Hello, World from Rust!");
}Kotlin implementation
fun main() {
println("Hello, World from Kotlin!")
}Swift implementation
import Foundation
print("Hello, World from Swift!")TypeScript implementation
function main(): void {
console.log("Hello, World from TypeScript!");
}
main();