Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare the adjacency list for the tree.
DSA Java
List<List<Integer>> tree = new ArrayList<>(); for (int i = 0; i < n; i++) { tree.[1](new ArrayList<>()); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using set() instead of add() causes IndexOutOfBoundsException.
Using get() or remove() does not add elements.
✗ Incorrect
We use the add() method to add a new empty list for each node in the adjacency list.
2fill in blank
mediumComplete the code to add an undirected edge between nodes u and v.
DSA Java
tree.get(u).[1](v);
tree.get(v).add(u);Attempts:
3 left
💡 Hint
Common Mistakes
Using remove() deletes elements instead of adding.
Using set() replaces existing elements, which is incorrect here.
✗ Incorrect
We use add() to insert the neighbor node into the adjacency list for undirected edges.
3fill in blank
hardFix the error in the DFS method signature to correctly pass the parent node.
DSA Java
private int dfs(int node, int [1], List<List<Integer>> tree, int[] dp) {Attempts:
3 left
💡 Hint
Common Mistakes
Using 'child' or 'root' confuses the traversal logic.
Using 'visited' as an int parameter is incorrect.
✗ Incorrect
The parent parameter helps avoid revisiting the node we came from during DFS.
4fill in blank
hardFill both blanks to update the diameter and dp values inside DFS.
DSA Java
for (int nei : tree.get(node)) { if (nei != [1]) { int dist = dfs(nei, node, tree, dp) + 1; diameter = Math.max(diameter, dp[node] + dist); dp[node] = Math.max(dp[node], [2]); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'nei' instead of 'parent' causes infinite recursion.
Updating dp[node] with 'nei' or 'node' instead of 'dist' is wrong.
✗ Incorrect
We skip the parent node to avoid cycles and update dp[node] with the maximum distance found.
5fill in blank
hardFill all three blanks to complete the method that returns the diameter of the tree.
DSA Java
public int treeDiameter(int n, int[][] edges) {
List<List<Integer>> tree = new ArrayList<>();
for (int i = 0; i < n; i++) tree.[1](new ArrayList<>());
for (int[] edge : edges) {
tree.get(edge[0]).[2](edge[1]);
tree.get(edge[1]).add(edge[0]);
}
dp = new int[n];
diameter = 0;
dfs(0, -1, tree, dp);
return [3];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using set() instead of add() causes errors.
Returning dp instead of diameter is incorrect.
✗ Incorrect
We add empty lists for each node, add edges using add(), and return the diameter after DFS.
