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 parameter name different from the field without assignment.
Forgetting to assign the parameter to the field.
✗ Incorrect
The constructor parameter should be named 'data' to match the assignment 'this.data = data;'.
2fill in blank
mediumComplete the code to initialize the horizontal distance map in the bottom view method.
DSA Java
Map<Integer, Integer> map = new TreeMap<>();
Queue<Pair<Node, Integer>> queue = new LinkedList<>();
queue.add(new Pair<>(root, [1]));Attempts:
3 left
💡 Hint
Common Mistakes
Starting horizontal distance at 1 or -1 instead of 0.
Using null which is invalid for an integer.
✗ Incorrect
The root node's horizontal distance is initialized to 0.
3fill in blank
hardFix the error in updating the map with the bottom view node data.
DSA Java
while (!queue.isEmpty()) { Pair<Node, Integer> temp = queue.poll(); Node node = temp.getKey(); int hd = temp.getValue(); map.put(hd, [1]); if (node.left != null) queue.add(new Pair<>(node.left, hd - 1)); if (node.right != null) queue.add(new Pair<>(node.right, hd + 1)); }
Attempts:
3 left
💡 Hint
Common Mistakes
Storing the horizontal distance instead of node data.
Storing the node object instead of its data.
✗ Incorrect
We store the node's data at the horizontal distance in the map for bottom view.
4fill in blank
hardFill both blanks to complete the method that returns the bottom view list.
DSA Java
public List<Integer> bottomView(Node root) {
List<Integer> result = new ArrayList<>();
if (root == null) return result;
Map<Integer, Integer> map = new TreeMap<>();
Queue<Pair<Node, Integer>> queue = new LinkedList<>();
queue.add(new Pair<>(root, 0));
while (!queue.isEmpty()) {
Pair<Node, Integer> temp = queue.poll();
Node node = temp.getKey();
int hd = temp.getValue();
map.put(hd, node.data);
if (node.left != null) queue.add(new Pair<>(node.left, hd [1] 1));
if (node.right != null) queue.add(new Pair<>(node.right, hd [2] 1));
}
for (int val : map.values()) result.add(val);
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using addition for left child or subtraction for right child.
Using multiplication or division which is incorrect.
✗ Incorrect
Left child horizontal distance is hd - 1; right child is hd + 1.
5fill in blank
hardFill all three blanks to complete the Pair class usage and map iteration.
DSA Java
Queue<Pair<Node, Integer>> queue = new LinkedList<>(); queue.add(new Pair<>([1], [2])); for (Map.Entry<Integer, Integer> entry : map.[3]()) { result.add(entry.getValue()); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using keySet() instead of entrySet() for map iteration.
Using null or wrong values in Pair constructor.
✗ Incorrect
We add root with horizontal distance 0; iterate map entries with entrySet().
