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 Java
Queue<Pair<TreeNode, Integer>> queue = new LinkedList<>(); queue.[1](new Pair<>(root, 0));
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'push' which is for stacks, not queues.
Using 'insert' which is not a Queue method.
✗ Incorrect
The 'offer' method adds an element to the queue safely and is preferred for queues in Java.
2fill in blank
mediumComplete the code to calculate the width of the current level.
DSA Java
int width = lastIndex - [1] + 1;
Attempts:
3 left
💡 Hint
Common Mistakes
Using levelSize instead of firstIndex.
Forgetting to add 1 to the difference.
✗ Incorrect
Width is calculated by subtracting the first index from the last index and adding 1.
3fill in blank
hardFix the error in the code to correctly assign the index to the left child node.
DSA Java
if (node.left != null) { queue.offer(new Pair<>(node.left, [1])); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using index * 2 + 1 for left child which is for right child.
Using index + 1 which is incorrect for binary tree indexing.
✗ Incorrect
Left child index is calculated as parent index * 2.
4fill in blank
hardFill both blanks to correctly assign the index to the right child node and update maxWidth.
DSA Java
if (node.right != null) { queue.offer(new Pair<>(node.right, [1])); } maxWidth = Math.[2](maxWidth, width);
Attempts:
3 left
💡 Hint
Common Mistakes
Using Math.min instead of Math.max.
Assigning wrong index to right child.
✗ Incorrect
Right child index is parent index * 2 + 1. maxWidth is updated using Math.max to keep the largest width.
5fill in blank
hardFill all three blanks to complete the loop that processes each level of the tree.
DSA Java
while (!queue.isEmpty()) { int size = queue.[1](); int firstIndex = queue.peek().getValue(); int lastIndex = 0; for (int i = 0; i < size; i++) { Pair<TreeNode, Integer> pair = queue.[2](); TreeNode node = pair.getKey(); int index = pair.getValue() - firstIndex; if (node.left != null) queue.offer(new Pair<>(node.left, index * 2)); if (node.right != null) queue.offer(new Pair<>(node.right, index * 2 + 1)); if (i == size - 1) lastIndex = index; } maxWidth = Math.max(maxWidth, [3]); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using peek() instead of poll() inside the loop.
Using wrong variable for width calculation.
✗ Incorrect
size is obtained by queue.size(), poll removes the head of the queue, and lastIndex is used to calculate width.
