0
0
DSA Javascriptprogramming~10 mins

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

DSA Javascript
let queue = [[root, [1]]];
Drag options to blanks, or click blank then click option'
A0
Bnull
C-1
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Starting index at 1 instead of 0
Using null as index
Using negative index
2fill in blank
medium

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

DSA Javascript
let width = lastIndex - firstIndex + [1];
Drag options to blanks, or click blank then click option'
A0
B-1
C1
D2
Attempts:
3 left
💡 Hint
Common Mistakes
Not adding 1 to the difference
Subtracting instead of adding
Using zero which undercounts width
3fill in blank
hard

Fix the error in the code that adds the left child to the queue with correct index.

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

Fill both blanks to add the right child to the queue with correct index and update maxWidth.

DSA Javascript
if (node.right) queue.push([node.right, [1]]);
maxWidth = Math.max(maxWidth, [2]);
Drag options to blanks, or click blank then click option'
Aindex * 2 + 1
Bwidth
ClastIndex - firstIndex + 1
Dindex * 2
Attempts:
3 left
💡 Hint
Common Mistakes
Using index * 2 for right child
Updating maxWidth with index instead of width
Not updating maxWidth at all
5fill in blank
hard

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

DSA Javascript
function widthOfBinaryTree(root) {
  if (!root) return 0;
  let maxWidth = 0;
  let queue = [[root, [1]]];
  while (queue.length) {
    let levelLength = queue.length;
    let firstIndex = queue[0][1];
    let lastIndex = queue[queue.length - 1][1];
    maxWidth = Math.max(maxWidth, lastIndex - firstIndex + [2]);
    for (let i = 0; i < levelLength; i++) {
      let [node, index] = queue.shift();
      index -= firstIndex;
      if (node.left) queue.push([node.left, index * 2 + [3]]);
      if (node.right) queue.push([node.right, index * 2 + 1]);
    }
  }
  return maxWidth;
}
Drag options to blanks, or click blank then click option'
A0
B1
Attempts:
3 left
💡 Hint
Common Mistakes
Starting index at 1
Not adding 1 to width
Using 1 instead of 0 for left child index offset