Maximum Width of Binary Tree in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to find the maximum width of a binary tree changes as the tree grows.
The question is: how does the work increase when the tree has more nodes?
Analyze the time complexity of the following code snippet.
function widthOfBinaryTree(root) {
if (!root) return 0;
let maxWidth = 0;
let queue = [[root, 0]]; // node with index
while (queue.length) {
const length = queue.length;
const start = queue[0][1];
let end = start;
for (let i = 0; i < length; i++) {
const [node, index] = queue.shift();
end = index;
if (node.left) queue.push([node.left, 2 * index + 1]);
if (node.right) queue.push([node.right, 2 * index + 2]);
}
maxWidth = Math.max(maxWidth, end - start + 1);
}
return maxWidth;
}
This code finds the maximum width of a binary tree by level-order traversal, tracking node positions.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop processes each node once, and the inner for loop visits all nodes at the current level.
- How many times: Each node is visited exactly once, so total operations grow with the number of nodes.
As the number of nodes (n) increases, the code visits each node once, so the work grows directly with n.
| 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 grows.
Time Complexity: O(n)
This means the time to find the maximum width grows in direct proportion to the number of nodes in the tree.
[X] Wrong: "The time depends on the tree height only because we process level by level."
[OK] Correct: Even though we go level by level, every node is visited once, so total time depends on total nodes, not just height.
Understanding how to analyze traversal algorithms like this helps you explain your approach clearly and shows you grasp how data size affects performance.
"What if we used a depth-first search instead of breadth-first search? How would the time complexity change?"