Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Starting index at 1 instead of 0
Using null as index
Using negative index
✗ Incorrect
The root node is assigned index 0 to start the level indexing from zero.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Not adding 1 to the difference
Subtracting instead of adding
Using zero which undercounts width
✗ Incorrect
Width is calculated as last index minus first index plus one to include both ends.
3fill in blank
hardFix 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'
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
✗ Incorrect
Left child's index is parent's index times 2 to maintain position in a full binary tree.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using index * 2 for right child
Updating maxWidth with index instead of width
Not updating maxWidth at all
✗ Incorrect
Right child's index is parent's index times 2 plus 1; maxWidth updates with current level width.
5fill in blank
hardFill 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'
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
✗ Incorrect
Start indexing at 0; add 1 to width calculation; left child index is index * 2 + 0.