Top View of Binary Tree in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to find the top view of a binary tree changes as the tree grows.
How does the number of nodes affect the work done to get the top view?
Analyze the time complexity of the following code snippet.
function topView(root) {
if (!root) return [];
const queue = [{ node: root, hd: 0 }];
const map = new Map();
while (queue.length) {
const { node, hd } = queue.shift();
if (!map.has(hd)) map.set(hd, node.val);
if (node.left) queue.push({ node: node.left, hd: hd - 1 });
if (node.right) queue.push({ node: node.right, hd: hd + 1 });
}
return Array.from(map.values());
}
This code finds the top view of a binary tree by visiting nodes level by level and tracking their horizontal distance.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that visits each node once.
- How many times: Once for every node in the tree (n times).
As the number of nodes grows, the code visits each node once, so the work grows directly with the number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The operations increase linearly as the tree size increases.
Time Complexity: O(n)
This means the time to find the top view grows in direct proportion to the number of nodes in the tree.
[X] Wrong: "The code visits nodes multiple times, so time is more than linear."
[OK] Correct: Each node is visited exactly once in the queue, so the total work is proportional to the number of nodes.
Understanding this linear time complexity helps you explain how tree traversal works efficiently in real problems.
"What if we used a recursive approach instead of a queue? How would the time complexity change?"