Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare the adjacency list for the tree.
DSA C#
[1]<int>[] tree = new [2]<int>[n]; for (int i = 0; i < n; i++) { tree[i] = new [3]<int>(); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using Stack or Queue instead of List for adjacency representation.
Using Dictionary which is not suitable for this adjacency list.
✗ Incorrect
We use List to store adjacency lists for each node in the tree.
2fill in blank
mediumComplete the code to add an undirected edge between nodes u and v.
DSA C#
tree[u].[1](v); tree[v].[2](u);
Attempts:
3 left
💡 Hint
Common Mistakes
Using Remove or Insert which are not for adding at the end.
Using Append which is not a List method in C#.
✗ Incorrect
We use Add method to add neighbors to the adjacency list in C#.
3fill in blank
hardFix the error in the DFS method signature to correctly pass the parent node.
DSA C#
int DFS(int node, int [1], List<int>[] tree, int[] dp) {
// DFS logic
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'child' or 'root' which do not represent the parent node.
Using 'visited' which is usually a boolean array, not an int.
✗ 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 calculate the longest path from the current node.
DSA C#
foreach (int child in tree[node]) { if (child != [1]) { int length = DFS(child, node, tree, dp) + 1; dp[node] = Math.Max(dp[node], length); diameter = Math.Max(diameter, dp[node] + [2]); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'child' in the first blank causes revisiting the same node.
Using dp[node] instead of dp[child] for diameter update is incorrect.
✗ Incorrect
We skip the parent node to avoid revisiting it, and use dp[child] to update the diameter.
5fill in blank
hardFill all three blanks to complete the DFS method that calculates the diameter of the tree.
DSA C#
int DFS(int node, int parent, List<int>[] tree, int[] dp) {
int max1 = 0, max2 = 0;
foreach (int child in tree[node]) {
if (child != [1]) {
int length = DFS(child, [2], tree, dp) + 1;
if (length > max1) { max2 = max1; max1 = length; }
else if (length > max2) { max2 = length; }
}
}
diameter = Math.Max(diameter, max1 + max2);
dp[[3]] = max1;
return dp[node];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'child' instead of 'parent' causes infinite recursion.
Using 'child' instead of 'node' for dp update is incorrect.
✗ Incorrect
The first two blanks are the parent to avoid revisiting it, and the last blank is node to store the longest path.
