Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare the Node class with integer data.
DSA Java
class Node { int data; Node left, right; Node(int [1]) { this.data = data; left = right = null; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different parameter name like 'value' without changing the assignment.
Forgetting to assign the parameter to the field.
✗ Incorrect
The constructor parameter should be named 'data' to assign it correctly to the node's data field.
2fill in blank
mediumComplete the code to add a node to the queue.
DSA Java
Queue<Node> queue = new LinkedList<>(); Node root = new Node(10); queue.[1](root);
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 is preferred for queues to add elements safely.
3fill in blank
hardFix the error in the code to get the horizontal distance from the map.
DSA Java
Map<Node, Integer> map = new HashMap<>(); int hd = [1](node, 0);
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'map.get(node)' which can return null and cause errors.
Using 'node' or 'map.get' incorrectly.
✗ Incorrect
Use 'map.getOrDefault(node, 0)' to avoid null if key is missing.
4fill in blank
hardFill both blanks to update the horizontal distance and add child nodes to the queue.
DSA Java
if (node.left != null) { map.put(node.left, map.get(node) [1] 1); queue.[2](node.left); }
Attempts:
3 left
💡 Hint
Common Mistakes
Adding instead of subtracting for left child distance.
Using 'add' instead of 'offer' for queue.
✗ Incorrect
Left child horizontal distance is parent's minus one; use 'offer' to add to queue.
5fill in blank
hardFill in the blanks to print the top view nodes in order.
DSA Java
for (Map.Entry<Integer, Integer> entry : map.[1]()) { System.out.print(entry.[2] + " "); } System.out.println();
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'key' instead of 'getValue()' to print node data.
Using 'values()' in the loop header which is not iterable as entries.
✗ Incorrect
Use 'entrySet()' to iterate, 'getValue()' to get node data, and 'values()' is incorrect here.
