Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using null or undefined instead of root.
Starting with an empty queue.
✗ Incorrect
We start the queue with the root node and index 0 to track positions in the tree.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 instead of 1, which undercounts width.
Using 2 or -1, which gives incorrect width.
✗ Incorrect
Width is calculated as last index minus first index plus one to count all nodes in between.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using index + 1 which is incorrect for left child.
Using index * 2 + 1 which is for right child.
✗ Incorrect
Left child index is calculated as parent index times 2 to maintain position.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using index * 2 which is for left child.
Using index + 1 which is incorrect for this calculation.
✗ Incorrect
Right child index is parent index times 2 plus 1 to keep correct position.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to add 1 in width calculation.
Swapping left and right child index offsets.
✗ Incorrect
Width calculation adds 1; left child index is normalizedIndex * 2 + 0; right child index is normalizedIndex * 2 + 1.