Bottom View of Binary Tree in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to find the bottom view of a binary tree changes as the tree grows.
How does the number of nodes affect the work done to get the bottom view?
Analyze the time complexity of the following code snippet.
function bottomView(root) {
if (!root) return [];
const queue = [{ node: root, hd: 0 }];
const map = new Map();
while (queue.length) {
const { node, hd } = queue.shift();
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 [...map.values()];
}
This code finds the bottom view of a binary tree by traversing nodes level by level and tracking horizontal distances.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that processes each node once.
- How many times: Exactly once per 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 and updates |
| 100 | About 100 visits and updates |
| 1000 | About 1000 visits and updates |
Pattern observation: The operations increase linearly as the tree size increases.
Time Complexity: O(n)
This means the time to find the bottom view grows in direct proportion to the number of nodes in the tree.
[X] Wrong: "The time complexity is more than linear because we update the map multiple times for the same horizontal distance."
[OK] Correct: Each node is processed once, and map updates happen once per node, so total work is still proportional to the number of nodes.
Understanding this linear time complexity helps you explain how tree traversals work efficiently and shows you can analyze algorithms that use queues and maps together.
"What if we used a recursive depth-first traversal instead of a queue? How would the time complexity change?"