Bottom View of Binary Tree in DSA Typescript - 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: TreeNode | null): number[] {
if (!root) return [];
const queue: Array<[TreeNode, number]> = [[root, 0]];
const map = new Map<number, number>();
while (queue.length) {
const [node, hd] = queue.shift()!;
map.set(hd, node.val);
if (node.left) queue.push([node.left, hd - 1]);
if (node.right) queue.push([node.right, hd + 1]);
}
return Array.from(map.entries())
.sort((a, b) => a[0] - b[0])
.map(entry => entry[1]);
}
This code finds the bottom view of a binary tree by level order traversal, tracking horizontal distances.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop processes each node once.
- How many times: Exactly once per node, so n times for n nodes.
- Inside the loop, map updates and queue operations happen once per node.
- Sorting the map entries happens once after traversal, with entries up to the number of unique horizontal distances.
As the tree grows, the number of nodes n increases, so the loop runs n times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 loop passes + sorting ~10 entries |
| 100 | About 100 loop passes + sorting ~100 entries |
| 1000 | About 1000 loop passes + sorting ~1000 entries |
Pattern observation: The operations grow roughly in direct proportion to n, with sorting adding a small extra cost.
Time Complexity: O(n log n)
This means the time grows a bit faster than the number of nodes because of sorting the horizontal distances after traversal.
[X] Wrong: "The time complexity is just O(n) because we visit each node once."
[OK] Correct: While visiting nodes is O(n), sorting the horizontal distances at the end takes extra time, making the total O(n log n).
Understanding this time complexity helps you explain how traversal and sorting combine in tree problems, a common skill interviewers look for.
"What if we used a balanced tree or priority queue to keep horizontal distances sorted during traversal? How would the time complexity change?"