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 like 'value' without changing the assignment causes errors.
✗ Incorrect
The constructor parameter should be named 'val' to assign it to the class variable val.
2fill in blank
mediumComplete the code to initialize the queue for BFS traversal.
DSA Java
Queue<Pair<TreeNode, Integer>> queue = new [1]<>();Attempts:
3 left
💡 Hint
Common Mistakes
Using Stack instead of Queue causes LIFO behavior, not BFS.
✗ Incorrect
LinkedList is used to implement Queue in Java for BFS traversal.
3fill in blank
hardFix the error in the code to add a node and its horizontal distance to the queue.
DSA Java
queue.[1](new Pair<>(node.left, hd - 1));
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'push' causes compile error as it's not a Queue method.
✗ Incorrect
The 'offer' method is preferred for adding elements to a queue in Java.
4fill in blank
hardFill both blanks to update the map with node values at each horizontal distance.
DSA Java
map.computeIfAbsent(hd, k -> new ArrayList<>()).[1](node.val);Attempts:
3 left
💡 Hint
Common Mistakes
Using 'put' causes compile error as it's not a List method.
✗ Incorrect
The 'add' method adds an element to the ArrayList at the given horizontal distance.
5fill in blank
hardFill both blanks to return the vertical order traversal as a list of lists.
DSA Java
List<List<Integer>> result = new ArrayList<>(); for (int key : new TreeSet<>(map.[1]())) { result.[2](map.get(key)); } return result;
Attempts:
3 left
💡 Hint
Common Mistakes
Using values() instead of keySet() causes wrong iteration order.
✗ Incorrect
We get keys with keySet(), add lists to result with add(), and map.get(key) returns values.
