0
0
DSA Typescriptprogramming~10 mins

Maximum Width of Binary Tree in DSA Typescript - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to initialize the queue with the root node and its index 0.

DSA Typescript
const queue: Array<[TreeNode | null, number]> = [[[1], 0]];
Drag options to blanks, or click blank then click option'
Aroot
B0
Cundefined
Dnull
Attempts:
3 left
💡 Hint
Common Mistakes
Using null or undefined instead of root.
Starting with an empty queue.
2fill in blank
medium

Complete the code to calculate the width of the current level.

DSA Typescript
const width = lastIndex - firstIndex + [1];
Drag options to blanks, or click blank then click option'
A1
B0
C-1
D2
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 instead of 1, which undercounts width.
Using 2 or -1, which gives incorrect width.
3fill in blank
hard

Fix the error in the code to add child nodes to the queue with correct indices.

DSA Typescript
if (node.left) queue.push([node.left, [1]]);
Drag options to blanks, or click blank then click option'
Aindex - 1
Bindex + 1
Cindex * 2 + 1
Dindex * 2
Attempts:
3 left
💡 Hint
Common Mistakes
Using index + 1 which is incorrect for left child.
Using index * 2 + 1 which is for right child.
4fill in blank
hard

Fill both blanks to add the right child node to the queue with correct index calculation.

DSA Typescript
if (node.right) queue.push([node.right, [1]]);
Drag options to blanks, or click blank then click option'
Aindex * 2
Bindex + 1
Cindex * 2 + 1
Dindex - 1
Attempts:
3 left
💡 Hint
Common Mistakes
Using index * 2 which is for left child.
Using index + 1 which is incorrect for this calculation.
5fill in blank
hard

Fill all three blanks to complete the function that returns the maximum width of the binary tree.

DSA Typescript
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 firstIndex = queue[0][1];
    const lastIndex = queue[levelLength - 1][1];
    maxWidth = Math.max(maxWidth, lastIndex - firstIndex + [1]);

    for (let i = 0; i < levelLength; i++) {
      const [node, index] = queue.shift()!;
      const normalizedIndex = index - firstIndex;
      if (node.left) queue.push([node.left, normalizedIndex * 2 + [2]]);
      if (node.right) queue.push([node.right, normalizedIndex * 2 + [3]]);
    }
  }

  return maxWidth;
}
Drag options to blanks, or click blank then click option'
A0
B1
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to add 1 in width calculation.
Swapping left and right child index offsets.