What if you could see a tree's hidden branches from above without climbing it?
Why Top View of Binary Tree in DSA Javascript?
Imagine you have a tall tree in your backyard. You want to see which branches are visible if you look at the tree from the top. If you try to list these branches by walking around the tree and guessing, it gets confusing fast.
Manually figuring out which branches are visible from the top is slow and confusing because branches overlap when viewed from above. You might miss some branches or count the same branch multiple times.
The top view of a binary tree helps you find exactly which nodes (branches) are visible from above by using a smart method that checks horizontal positions. This way, you get a clear list of visible nodes without guessing.
function manualTopView(tree) {
// Try to guess visible nodes by walking
// This is slow and error-prone
let visible = [];
// No clear method here
return visible;
}function topView(root) {
let queue = [{ node: root, hd: 0 }];
let map = new Map();
while (queue.length) {
let { node, hd } = queue.shift();
if (!map.has(hd)) map.set(hd, node.data);
if (node.left) queue.push({ node: node.left, hd: hd - 1 });
if (node.right) queue.push({ node: node.right, hd: hd + 1 });
}
return [...map.values()];
}This concept lets you quickly find all nodes visible from the top of a binary tree, making complex tree views easy to understand and use.
In city planning, when looking at buildings from above, top view helps decide which buildings are visible and which are hidden behind others.
Manual guessing of top view is confusing and slow.
Top view uses horizontal distances to find visible nodes.
This method gives a clear, quick list of visible nodes from above.
Practice
top view of a binary tree represent?Solution
Step 1: Understand the top view concept
The top view of a binary tree shows nodes visible from above, ignoring nodes hidden behind others.Step 2: Compare with other views
Left or right views show nodes from sides, and leaf nodes are only the bottom nodes.Final Answer:
Nodes visible when the tree is viewed from above -> Option DQuick Check:
Top view = nodes seen from above [OK]
- Confusing top view with left or right view
- Thinking top view includes all leaf nodes
- Assuming top view shows all nodes
Solution
Step 1: Identify the need for key-value pairs
We need to store nodes with their horizontal distance as keys and node values as values.Step 2: Choose the best data structure
A Map allows storing key-value pairs with efficient lookup and insertion.Final Answer:
Map -> Option CQuick Check:
Map stores horizontal distance keys [OK]
- Using Array which is index-based, not key-based
- Using Set which stores only unique values without keys
- Using Stack which is LIFO, not suitable here
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
function topView(root) {
if (!root) return [];
const map = new Map();
const queue = [{ node: root, hd: 0 }];
while (queue.length) {
const { node, hd } = queue.shift();
if (!map.has(hd)) map.set(hd, node.data);
if (node.left) queue.push({ node: node.left, hd: hd - 1 });
if (node.right) queue.push({ node: node.right, hd: hd + 1 });
}
return [...map.entries()]
.sort((a, b) => a[0] - b[0])
.map(entry => entry[1]);
}
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.right = new Node(4);
root.right.right = new Node(5);
console.log(topView(root));Solution
Step 1: Traverse the tree with horizontal distances
Start at root (1) with hd=0, add left child (2) hd=-1, right child (3) hd=1, then 4 at hd=0 (ignored since hd=0 exists), 5 at hd=2.Step 2: Collect first nodes at each horizontal distance
Map stores hd:-1=2, hd:0=1, hd:1=3, hd:2=5. Sorted by hd: -1,0,1,2 gives [2,1,3,5].Final Answer:
[2, 1, 3, 5] -> Option AQuick Check:
Top view nodes by hd = [2,1,3,5] [OK]
- Including nodes hidden behind others at same hd
- Not sorting by horizontal distance before output
- Adding nodes multiple times for same hd
function topView(root) {
if (!root) return [];
const map = new Map();
const queue = [{ node: root, hd: 0 }];
while (queue.length) {
const { node, hd } = queue.pop();
if (!map.has(hd)) map.set(hd, node.data);
if (node.left) queue.push({ node: node.left, hd: hd - 1 });
if (node.right) queue.push({ node: node.right, hd: hd + 1 });
}
return [...map.entries()]
.sort((a, b) => a[0] - b[0])
.map(entry => entry[1]);
}Solution
Step 1: Understand queue usage in BFS
Using queue.pop() removes last element, making it a stack (DFS), not BFS. BFS requires queue.shift() to process nodes in FIFO order.Step 2: Fix the traversal order
Replacing pop() with shift() ensures nodes are processed level by level, correctly capturing top view nodes.Final Answer:
Replace queue.pop() with queue.shift() to process nodes in correct order -> Option AQuick Check:
BFS needs shift(), not pop() [OK]
- Using pop() causing wrong traversal order
- Using Set instead of Map losing key-value pairs
- Skipping sorting which orders output incorrectly
Solution
Step 1: Understand node conflicts at same horizontal distance and level
When nodes share horizontal distance and level, top view includes the first encountered node in level order (BFS) traversal.Step 2: Reason why first node is chosen
Because BFS visits nodes level by level from left to right, the first node at that horizontal distance is visible from top.Final Answer:
Include the node that appears first in level order traversal at that horizontal distance -> Option BQuick Check:
Top view = first node at hd in BFS order [OK]
- Choosing node by max value instead of order
- Including all nodes causing duplicates
- Choosing last node instead of first
Ready to prove it?
Pass the test and this pattern moves unknown
