Complete the code to initialize the adjacency list for the tree.
adj := make([][]int, [1])We create an adjacency list with size equal to the number of nodes n.
Complete the code to add edges to the adjacency list.
adj[u] = append(adj[u], [1])
adj[v] = append(adj[v], u)We add node v to the adjacency list of u to represent the edge.
Fix the error in the DFS function signature to correctly pass the parent node.
func dfs(node int, parent int) int {
max1, max2 := 0, 0
for _, child := range adj[node] {
if child == [1] {
continue
}
dist := dfs(child, node) + 1
if dist > max1 {
max2 = max1
max1 = dist
} else if dist > max2 {
max2 = dist
}
}
diameter = max(diameter, max1+max2)
return max1
}We skip the parent node to avoid revisiting it in DFS.
Fill both blanks to update the diameter and return the longest path from the current node.
diameter = max(diameter, [1] + [2]) return max1
The diameter is updated by the sum of the two longest paths from the current node.
Fill all three blanks to complete the main function that computes the diameter of the tree.
func treeDiameter(n int, edges [][]int) int {
adj := make([][]int, [1])
for _, e := range edges {
u, v := e[0], e[1]
adj[u] = append(adj[u], [2])
adj[v] = append(adj[v], u)
}
diameter := 0
dfs(0, [3])
return diameter
}Initialize adjacency list with size n, append v to adj[u], and start DFS from node 0 with parent -1.
