0
0
DSA Typescriptprogramming~5 mins

Maximum Width of Binary Tree in DSA Typescript - 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.

How does the number of nodes affect the work done?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function widthOfBinaryTree(root: TreeNode | null): number {
  if (!root) return 0;
  let maxWidth = 0;
  const queue: Array<[TreeNode, number]> = [[root, 0]];
  while (queue.length > 0) {
    const levelLength = queue.length;
    const levelHeadIndex = queue[0][1];
    for (let i = 0; i < levelLength; i++) {
      const [node, index] = queue.shift()!;
      if (node.left) queue.push([node.left, 2 * (index - levelHeadIndex)]);
      if (node.right) queue.push([node.right, 2 * (index - levelHeadIndex) + 1]);
    }
    const levelTailIndex = queue.length > 0 ? queue[queue.length - 1][1] : 0;
    maxWidth = Math.max(maxWidth, levelTailIndex + 1);
  }
  return maxWidth;
}
    

This code finds the maximum width of a binary tree by traversing each level and tracking node positions.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The while loop processes each level of the tree, and the inner for loop visits every node at that level.
  • How many times: Each node is visited exactly once during the traversal.
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 number of operations grows 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 height of the tree only because we process level by level."

[OK] Correct: Even though we go level by level, every node is still visited once, so the total work depends on the total number of nodes, not just the height.

Interview Connect

Understanding how tree traversal time grows helps you explain your approach clearly and shows you know how to analyze algorithms well.

Self-Check

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