Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare the adjacency list for the tree.
DSA C++
vector<int> adj[[1]];Attempts:
3 left
💡 Hint
Common Mistakes
Using number of edges instead of nodes for adjacency list size.
✗ Incorrect
The adjacency list size should be equal to the number of nodes 'n' in the tree.
2fill in blank
mediumComplete the code to update the diameter during DFS traversal.
DSA C++
diameter = max(diameter, dist1 + dist2 + [1]);
Attempts:
3 left
💡 Hint
Common Mistakes
Adding 1 or 2 instead of 0, causing off-by-one errors.
✗ Incorrect
No additional value is needed because dist1 and dist2 represent the lengths of the two longest downward paths from the current node, and their sum gives the diameter through this node.
3fill in blank
hardFix the error in the DFS function to correctly compute the longest path from the current node.
DSA C++
int dfs(int node, int parent) {
int max_depth = 0;
for (int child : adj[node]) {
if (child == [1]) continue;
int depth = dfs(child, node) + 1;
max_depth = max(max_depth, depth);
}
return max_depth;
}Attempts:
3 left
💡 Hint
Common Mistakes
Skipping the current node or child instead of the parent.
✗ Incorrect
We skip the parent node to avoid revisiting it and causing infinite recursion.
4fill in blank
hardFill both blanks to update the two longest depths from children in the DFS.
DSA C++
int dfs(int node, int parent) {
int max1 = 0, max2 = 0;
for (int child : adj[node]) {
if (child == parent) continue;
int depth = dfs(child, node) + 1;
if (depth > [1]) {
[2] = max1;
max1 = depth;
} else if (depth > max2) {
max2 = depth;
}
}
diameter = max(diameter, max1 + max2);
return max1;
}Attempts:
3 left
💡 Hint
Common Mistakes
Swapping max1 and max2 incorrectly or using wrong variables.
✗ Incorrect
We compare depth with max1, then assign max2 to old max1 before updating max1.
5fill in blank
hardFill all three blanks to implement the diameter calculation using DFS.
DSA C++
int diameter = 0; int dfs(int node, int parent) { int max1 = 0, max2 = 0; for (int child : adj[node]) { if (child == parent) continue; int depth = dfs(child, node) + [1]; if (depth > max1) { max2 = max1; max1 = depth; } else if (depth > max2) { max2 = depth; } } diameter = max(diameter, max1 + max2 + [2]); return max1 + [3]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Adding 1 or 2 incorrectly causing off-by-one errors.
✗ Incorrect
Add 1 for edge length when going down, add 0 when updating diameter (already counted), and add 0 when returning max1.
