Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare the TreeNode class with integer value.
DSA Java
class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int [1]) { this.val = val; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different parameter name than 'val' causes the assignment to not work as intended.
✗ Incorrect
The constructor parameter should be named 'val' to match the assignment 'this.val = val;'.
2fill in blank
mediumComplete the code to start the left side view traversal using a queue.
DSA Java
Queue<TreeNode> queue = new LinkedList<>();
queue.[1](root);Attempts:
3 left
💡 Hint
Common Mistakes
Using 'push' which is for stacks, not queues.
Using 'enqueue' which is not a Java Queue method.
✗ Incorrect
The 'add' method is used to insert elements into a Java Queue.
3fill in blank
hardFix the error in the loop condition to process nodes level by level.
DSA Java
while (!queue.[1]()) { int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode node = queue.poll(); // process node } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'empty' which does not exist for Queue.
Using 'hasNext' which is for iterators.
✗ Incorrect
The correct method to check if a queue is empty is 'isEmpty()'.
4fill in blank
hardFill both blanks to add left and right children to the queue if they exist.
DSA Java
if (node.[1] != null) queue.[2](node.left); if (node.right != null) queue.add(node.right);
Attempts:
3 left
💡 Hint
Common Mistakes
Checking 'right' instead of 'left' for the first blank.
Using 'add' instead of 'offer' inconsistently.
✗ Incorrect
Check if 'left' child exists, then add it to the queue using 'offer' method.
5fill in blank
hardFill all three blanks to add the first node's value of each level to the result list.
DSA Java
List<Integer> result = new ArrayList<>(); while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode node = queue.poll(); if (i == [1]) result.[2](node.[3]); if (node.left != null) queue.offer(node.left); if (node.right != null) queue.offer(node.right); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '1' instead of '0' for the first node index.
Using 'set' instead of 'add' for the list.
Accessing 'value' instead of 'val' field.
✗ Incorrect
The first node in each level has index 0; add its 'val' to the result list using 'add' method.
