The Top View of Binary Tree problem asks us to return the set of nodes visible when looking at the binary tree from above.
- Each node has a horizontal distance (HD) from the root:
- Root →
HD = 0 - Left child →
HD - 1 - Right child →
HD + 1
- Root →
- For each HD, the first node encountered during level-order traversal (BFS) is part of the top view.
We must output the nodes from leftmost HD to rightmost HD.
Here’s the [Problem Link] to begin with.
Example
Example 1
Input:
1
/ \
2 3
\
4
\
5
\
6
Output: [2, 1, 3, 6]
Explanation: From the top, nodes 2, 1, 3, and 6 are visible.Example 2
Input:
10
/ \
20 30
/ \
40 60
Output: [40, 20, 10, 30]Interactive Visualizer: BFS with Horizontal Distance
Pick an example or type a tree in level order (use null for missing children), then press Next. Each visited node shows its horizontal distance (hd); green nodes are the ones visible from the top.
Intuition and Approach
The key idea is to track the horizontal distance (HD) of each node during traversal.
- Start with the root at
HD = 0. - Use BFS (level-order traversal) to ensure that the first node at each HD is captured.
- Maintain a dictionary
hd_mapwhere:- Key = HD
- Value = Node data
- Only store the first occurrence of each HD.
- Traverse the entire tree, updating left and right children with HD – 1 and HD + 1.
- Sort keys of
hd_mapand return values in order.
This guarantees that we collect the correct top view.
Code Implementation
# Tree Node
# class Node:
# def __init__(self, val):
# self.right = None
# self.data = val
# self.left = None
from collections import deque
class Solution:
def topView(self, root):
if not root:
return []
# dictionary to store first node for each horizontal distance
hd_map = {}
# queue for BFS -> stores (node, horizontal_distance)
q = deque([(root, 0)])
while q:
node, hd = q.popleft()
# store the first node we encounter at this HD
if hd not in hd_map:
hd_map[hd] = node.data
# add left and right children with updated HD
if node.left:
q.append((node.left, hd - 1))
if node.right:
q.append((node.right, hd + 1))
# extract results sorted by horizontal distance
result = [hd_map[key] for key in sorted(hd_map.keys())]
return result/* Tree Node
class Node {
int data;
Node left, right;
Node(int val) { data = val; left = right = null; }
} */
class Solution {
static ArrayList<Integer> topView(Node root) {
ArrayList<Integer> result = new ArrayList<>();
if (root == null) return result;
// map to store first node for each horizontal distance (TreeMap keeps HDs sorted)
Map<Integer, Integer> hdMap = new TreeMap<>();
// queue for BFS -> stores (node, horizontal_distance)
Queue<Node> q = new LinkedList<>();
Queue<Integer> hds = new LinkedList<>();
q.add(root);
hds.add(0);
while (!q.isEmpty()) {
Node node = q.poll();
int hd = hds.poll();
// store the first node we encounter at this HD
hdMap.putIfAbsent(hd, node.data);
// add left and right children with updated HD
if (node.left != null) { q.add(node.left); hds.add(hd - 1); }
if (node.right != null) { q.add(node.right); hds.add(hd + 1); }
}
// extract results sorted by horizontal distance
result.addAll(hdMap.values());
return result;
}
}/* Tree Node
struct Node {
int data;
Node* left;
Node* right;
}; */
class Solution {
public:
vector<int> topView(Node* root) {
if (!root) return {};
// map to store first node for each horizontal distance (std::map keeps HDs sorted)
map<int, int> hdMap;
// queue for BFS -> stores (node, horizontal_distance)
queue<pair<Node*, int>> q;
q.push({root, 0});
while (!q.empty()) {
auto [node, hd] = q.front();
q.pop();
// store the first node we encounter at this HD
if (hdMap.find(hd) == hdMap.end()) {
hdMap[hd] = node->data;
}
// add left and right children with updated HD
if (node->left) q.push({node->left, hd - 1});
if (node->right) q.push({node->right, hd + 1});
}
// extract results sorted by horizontal distance
vector<int> result;
for (auto& [hd, val] : hdMap) result.push_back(val);
return result;
}
};Code Explanation
- BFS Traversal:
- Uses a queue to traverse the tree level by level.
- Horizontal Distance (HD):
- Root =
0, left child =-1, right child =+1.
- Root =
- hd_map:
- Captures only the first node at each HD.
- Ensures top-most node is chosen.
- Sorting:
- Keys are sorted to print nodes from leftmost to rightmost.
Dry Run
Input Tree:
1
/ \
2 3
\
4
\
5
\
6Step-by-step BFS traversal:
- Start → (1, 0) → store
hd_map[0] = 1. - Left → (2, -1) → store
hd_map[-1] = 2. - Right → (3, +1) → store
hd_map[1] = 3. - Next → (4, 0) → already exists, ignore.
- Next → (5, 1) → already exists, ignore.
- Next → (6, 2) → store
hd_map[2] = 6.
Final hd_map = {-1:2, 0:1, 1:3, 2:6}
Sorted output = [2, 1, 3, 6]
Time and Space Complexity
- Time Complexity:
- BFS traversal → O(N)
- Sorting keys of
hd_map→ O(K log K), where K = number of unique HDs - Total → O(N log K)
- Space Complexity:
- Dictionary for storing nodes → O(K)
- Queue for BFS → O(N)
- Total → O(N)
Conclusion
The Top View of Binary Tree problem is solved efficiently using BFS and horizontal distance mapping.
- Each node is assigned an HD.
- The first node encountered at each HD is chosen.
- Sorting ensures correct left-to-right order.
This method runs in O(N log K) time and O(N) space, making it optimal for large binary trees.
Frequently Asked Questions
What is the top view of a binary tree?
It is the set of nodes you would see looking at the tree from above, listed from left to right. For each horizontal position only the highest node is visible.
What is horizontal distance in a binary tree?
The root has horizontal distance (HD) 0. Moving to a left child subtracts 1 and moving to a right child adds 1. Nodes with the same HD sit in the same vertical column.
Why is BFS used instead of DFS for the top view?
BFS visits nodes level by level, so the first node it reaches at each HD is always the highest one. A plain DFS can reach a deeper node first, so it would need extra depth tracking to get the right answer.
What is the time complexity of the top view solution?
BFS visits every node once, which is O(n). Sorting the HD keys adds O(w log w), where w is the width of the tree. You can make it O(n) by tracking the minimum and maximum HD instead of sorting.
What is the difference between the top view and the bottom view?
The top view keeps the first node seen at each HD during BFS. The bottom view keeps the last one, so you simply overwrite the map entry every time instead of skipping it.
For any changes to the article, kindly email at co**@**********ug.in or contact us at +91-9712928220.
