0
0
DSA Javascriptprogramming~5 mins

Maximum Width of Binary Tree in DSA Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Maximum Width of Binary Tree
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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
10About 10 visits
100About 100 visits
1000About 1000 visits

Pattern observation: The operations increase linearly as the tree size grows.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding how to analyze traversal algorithms like this helps you explain your approach clearly and shows you grasp how data size affects performance.

Self-Check

"What if we used a depth-first search instead of breadth-first search? How would the time complexity change?"