Complete the code to initialize the adjacency list for the tree.
adj = [[] for _ in range([1])]
We use n+1 because nodes are numbered from 1 to n, so we need an extra slot for 1-based indexing.
Complete the code to add an undirected edge between nodes u and v.
adj[u].[1](v)
adj[v].append(u)We use append to add a single element to the adjacency list for node u.
Fix the error in the DFS function to avoid revisiting the parent node.
def dfs(node, parent): for neighbor in adj[node]: if neighbor != [1]: dfs(neighbor, node)
We skip the parent node to avoid going back and causing infinite recursion.
Fill both blanks to update the diameter and return the longest path length from the current node.
def dfs(node, parent): max1 = max2 = 0 for neighbor in adj[node]: if neighbor != parent: length = dfs(neighbor, node) + 1 if length > max1: max2 = max1 max1 = [1] elif length > max2: max2 = [2] global diameter diameter = max(diameter, max1 + max2) return max1
We update max1 and max2 with the new length if it is greater than the current max values.
Fill all three blanks to compute the diameter of the tree using DFS.
def tree_diameter(n, edges): global adj, diameter adj = [[] for _ in range([1])] for u, v in edges: adj[u].append(v) adj[v].append(u) diameter = 0 dfs([2], -1) return [3]
We create adjacency list with n+1 for 1-based nodes, start DFS from node 1, and return the global diameter.
