Bird
Raised Fist0
DSA Typescriptprogramming

Maximum Width of Binary Tree in DSA Typescript

Choose your learning style10 modes available
Mental Model
We want to find the widest level in a tree by counting nodes including gaps between them.
Analogy: Imagine a tree as a family photo where some people are missing but their spots remain empty; the width counts all spots from leftmost to rightmost person including empty spots.
       1
      / \
     2   3
    /     \
   4       5

Levels:
Level 0: 1
Level 1: 2 -> 3
Level 2: 4 -> null -> null -> 5
Dry Run Walkthrough
Input: Binary tree: 1 -> 2, 3 -> 4 (left child of 2), 5 (right child of 3)
Goal: Find the maximum width among all levels, counting null spots between nodes
Step 1: Start at root (level 0), assign index 0
Level 0: [0]1
Width = 1 (only one node)
Why: We begin counting from the root with index 0 to track positions
Step 2: Move to level 1, assign indices: left child 2 -> 0*2=0, right child 3 -> 0*2+1=1
Level 1: [0]2 -> [1]3
Width = 2 (nodes at indices 0 and 1)
Why: Indices help us count gaps between nodes even if some are missing
Step 3: Move to level 2, assign indices for children: 4 (left child of 2) -> 0*2=0, no right child of 2, no left child of 3, 5 (right child of 3) -> 1*2+1=3
Level 2: [0]4 -> null -> null -> [3]5
Width = 4 (indices 0 to 3)
Why: Counting indices including null spots shows the true width
Result:
Maximum width is 4 at level 2
Level 2: 4 -> null -> null -> 5
Annotated Code
DSA Typescript
class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
    this.val = val === undefined ? 0 : val;
    this.left = left === undefined ? null : left;
    this.right = right === undefined ? null : right;
  }
}

function widthOfBinaryTree(root: TreeNode | null): number {
  if (!root) return 0;
  let maxWidth = 0;
  // Queue holds pairs of node and its index
  const queue: Array<[TreeNode, number]> = [[root, 0]];

  while (queue.length > 0) {
    const levelLength = queue.length;
    const levelIndices = queue.map(pair => pair[1]);
    const levelMin = levelIndices[0];
    const levelMax = levelIndices[levelIndices.length - 1];
    maxWidth = Math.max(maxWidth, levelMax - levelMin + 1);

    for (let i = 0; i < levelLength; i++) {
      const [node, index] = queue.shift()!;
      // Normalize index to prevent overflow
      const normalizedIndex = index - levelMin;
      if (node.left) queue.push([node.left, 2 * normalizedIndex]);
      if (node.right) queue.push([node.right, 2 * normalizedIndex + 1]);
    }
  }
  return maxWidth;
}

// Driver code
const root = new TreeNode(1,
  new TreeNode(2, new TreeNode(4), null),
  new TreeNode(3, null, new TreeNode(5))
);
console.log(widthOfBinaryTree(root));
const queue: Array<[TreeNode, number]> = [[root, 0]];
Initialize queue with root node and index 0 to track positions
const levelIndices = queue.map(pair => pair[1]);
Collect indices of nodes at current level to calculate width
const levelMin = levelIndices[0]; const levelMax = levelIndices[levelIndices.length - 1];
Find leftmost and rightmost indices to measure width
maxWidth = Math.max(maxWidth, levelMax - levelMin + 1);
Update maximum width if current level is wider
const [node, index] = queue.shift()!; const normalizedIndex = index - levelMin;
Remove node from queue and normalize index to avoid large numbers
if (node.left) queue.push([node.left, 2 * normalizedIndex]); if (node.right) queue.push([node.right, 2 * normalizedIndex + 1]);
Add children to queue with calculated indices to keep track of positions
OutputSuccess
4
Complexity Analysis
Time: O(n) because we visit each node once during level order traversal
Space: O(n) because the queue can hold up to all nodes at the widest level
vs Alternative: Compared to naive level counting without indices, this method counts gaps correctly and avoids missing width caused by null nodes
Edge Cases
Empty tree
Returns 0 as there are no nodes
DSA Typescript
if (!root) return 0;
Tree with only root node
Returns 1 as width is just the root
DSA Typescript
maxWidth = Math.max(maxWidth, levelMax - levelMin + 1);
Tree with missing children causing gaps
Correctly counts width including null gaps using indices
DSA Typescript
const normalizedIndex = index - levelMin;
When to Use This Pattern
When asked for the widest level in a tree including gaps, use level order traversal with position indices to track node positions and calculate width.
Common Mistakes
Mistake: Counting only existing nodes at each level without considering gaps
Fix: Use indices to track positions and calculate width as rightmost index minus leftmost index plus one
Summary
Finds the maximum width of a binary tree including gaps between nodes.
Use when you need to measure the widest level in a tree counting empty spots.
Assign indices to nodes during level order traversal to track positions and calculate width accurately.

Practice

(1/5)
1. What does the "maximum width" of a binary tree represent?
easy
A. The largest number of nodes present at any single level of the tree
B. The height of the tree from root to the deepest leaf
C. The total number of nodes in the tree
D. The sum of values of all nodes at the widest level

Solution

  1. Step 1: Understand the definition of width in a binary tree

    The width is the count of nodes at a particular level in the tree.
  2. Step 2: Identify maximum width

    The maximum width is the largest such count among all levels.
  3. Final Answer:

    The largest number of nodes present at any single level of the tree -> Option A
  4. Quick Check:

    Maximum width = max nodes at any level [OK]
Hint: Width means count of nodes at one level, not height or sum [OK]
Common Mistakes:
  • Confusing width with height of the tree
  • Thinking width is total nodes in the tree
  • Assuming width is sum of node values
2. Which TypeScript data structure is best suited to track nodes level by level when finding maximum width of a binary tree?
easy
A. Queue
B. Stack
C. Set
D. Map

Solution

  1. Step 1: Identify traversal method for levels

    Level order traversal visits nodes level by level, which uses a queue.
  2. Step 2: Choose data structure for level order

    A queue allows FIFO order, perfect for processing nodes in each level sequentially.
  3. Final Answer:

    Queue -> Option A
  4. Quick Check:

    Level order traversal uses queue [OK]
Hint: Use queue for level-by-level traversal [OK]
Common Mistakes:
  • Using stack which is LIFO, not suitable for level order
  • Using set which doesn't maintain order
  • Using map which is key-value, not for traversal order
3. What will be the output of the following TypeScript code snippet that calculates maximum width of a binary tree?
class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val: number) {
    this.val = val;
    this.left = null;
    this.right = null;
  }
}

const root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.right.right = new TreeNode(5);

function maxWidth(root: TreeNode | null): number {
  if (!root) return 0;
  const queue: Array<TreeNode> = [root];
  let maxWidth = 0;
  while (queue.length > 0) {
    const levelSize = queue.length;
    maxWidth = Math.max(maxWidth, levelSize);
    for (let i = 0; i < levelSize; i++) {
      const node = queue.shift()!;
      if (node.left) queue.push(node.left);
      if (node.right) queue.push(node.right);
    }
  }
  return maxWidth;
}

console.log(maxWidth(root));
medium
A. 3
B. 2
C. 1
D. 4

Solution

  1. Step 1: Analyze tree structure and levels

    Level 1: Node 1 (width 1) Level 2: Nodes 2, 3 (width 2) Level 3: Nodes 4, 5 (width 2)
  2. Step 2: Check code logic for max width

    Code tracks queue length per level and updates maxWidth. Max width found is 2 at levels 2 and 3.
  3. Final Answer:

    2 -> Option B
  4. Quick Check:

    Max width = 2 nodes at widest level [OK]
Hint: Count nodes per level, track max count [OK]
Common Mistakes:
  • Counting total nodes instead of per level
  • Assuming width is height of tree
  • Ignoring null children in width calculation
4. The following TypeScript function aims to find the maximum width of a binary tree but has a bug. What is the bug?
function maxWidth(root: TreeNode | null): number {
  if (!root) return 0;
  const queue: Array<TreeNode> = [root];
  let maxWidth = 0;
  while (queue.length > 0) {
    const levelSize = queue.length;
    maxWidth = Math.max(maxWidth, levelSize);
    for (let i = 0; i <= levelSize; i++) {
      const node = queue.shift()!;
      if (node.left) queue.push(node.left);
      if (node.right) queue.push(node.right);
    }
  }
  return maxWidth;
}
medium
A. The maxWidth should be updated after the for loop
B. The queue should be a stack for correct traversal
C. The for loop condition should be i < levelSize, not i <= levelSize
D. The function should return queue.length instead of maxWidth

Solution

  1. Step 1: Examine the for loop condition

    The loop runs from i = 0 to i <= levelSize, which means it runs levelSize + 1 times.
  2. Step 2: Identify impact of off-by-one error

    Calling queue.shift() one extra time causes undefined or error because queue is empty after levelSize removals.
  3. Final Answer:

    The for loop condition should be i < levelSize, not i <= levelSize -> Option C
  4. Quick Check:

    Loop runs exactly levelSize times [OK]
Hint: Use i < levelSize for loops over fixed-size levels [OK]
Common Mistakes:
  • Using <= instead of < in loops causing extra iteration
  • Confusing queue with stack for level order
  • Updating maxWidth inside loop incorrectly
5. Given a binary tree where some nodes are missing (null), how can you modify the maximum width calculation to include the 'null' positions between nodes, so the width counts the distance between the leftmost and rightmost non-null nodes at each level? Choose the best approach to solve this problem in TypeScript.
hard
A. Count only non-null nodes per level ignoring positions
B. Calculate width by summing values of nodes at each level
C. Use a stack instead of a queue to track nodes
D. Assign an index to each node as if the tree was a complete binary tree, then calculate width as rightmost index - leftmost index + 1 per level

Solution

  1. Step 1: Understand the problem with missing nodes

    Simply counting nodes misses gaps caused by nulls, so width must consider positions.
  2. Step 2: Use indexing like a complete binary tree

    Assign indices to nodes: root = 0, left child = 2*index, right child = 2*index + 1. Track min and max indices per level to find width including gaps.
  3. Final Answer:

    Assign an index to each node as if the tree was a complete binary tree, then calculate width as rightmost index - leftmost index + 1 per level -> Option D
  4. Quick Check:

    Index nodes to include null gaps [OK]
Hint: Use complete tree indexing to count gaps [OK]
Common Mistakes:
  • Ignoring null gaps and counting only nodes
  • Using stack which breaks level order
  • Summing node values instead of counting width
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard