Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to add the root node to the queue for level order traversal.
DSA Java
Queue<TreeNode> queue = new LinkedList<>();
queue.[1](root);Attempts:
3 left
💡 Hint
Common Mistakes
Using remove() instead of add() to insert the root.
Using peek() which only views the element without adding.
Using poll() which removes the element instead of adding.
✗ Incorrect
We use queue.add(root) to start the level order traversal by adding the root node to the queue.
2fill in blank
mediumComplete the code to get the current node from the queue during traversal.
DSA Java
TreeNode current = queue.[1]();Attempts:
3 left
💡 Hint
Common Mistakes
Using add() which inserts instead of removing.
Using offer() which inserts instead of removing.
Using peek() which only views without removing.
✗ Incorrect
queue.poll() removes and returns the head of the queue, which is the current node to process.
3fill in blank
hardFix the error in adding the left child node to the queue only if it exists.
DSA Java
if (current.[1] != null) { queue.add(current.left); }
Attempts:
3 left
💡 Hint
Common Mistakes
Checking current.right instead of current.left.
Using a non-existent property like 'parent' or 'child'.
✗ Incorrect
We check if current.left is not null before adding it to the queue to avoid errors.
4fill in blank
hardFill both blanks to complete the loop that processes nodes until the queue is empty.
DSA Java
while (!queue.[1]()) { TreeNode current = queue.[2](); // process current }
Attempts:
3 left
💡 Hint
Common Mistakes
Using peek() instead of poll() to remove nodes.
Using add() inside the while condition which is incorrect.
✗ Incorrect
The loop continues while the queue is not empty (isEmpty() returns false). Inside, poll() removes the current node.
5fill in blank
hardFill all three blanks to build a map of node values to their level during BFS traversal.
DSA Java
Map<TreeNode, Integer> levels = new HashMap<>(); levels.put(root, [1]); Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { TreeNode current = queue.poll(); int currentLevel = levels.get(current); if (current.left != null) { queue.add(current.left); levels.put(current.left, currentLevel [2] [3]); } if (current.right != null) { queue.add(current.right); levels.put(current.right, currentLevel [2] [3]); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Starting root level at 1 instead of 0.
Subtracting 1 instead of adding 1 for child levels.
Using multiplication or other operators instead of addition.
✗ Incorrect
The root is at level 0. Each child is at parent's level + 1, so we add 1 to currentLevel.
