Here's the full solution:
function treeDiameter(adj, n)
diameter := 0
function dfs(v, parent)
max1 := 0, max2 := 0
// two longest paths down
for each child in adj[v]
if child ≠ parent then
depth := dfs(child, v) + 1
if depth > max1 then
max2 := max1
max1 := depth
else if depth > max2 then
max2 := depth
diameter := max(diameter, max1 + max2)
return max1
dfs(0, -1)
return diameter
Time: . You visit each node once. The trick is tracking the two longest paths to compute the diameter through that node. Space: for adjacency list plus recursion stack.
Time complexity: .
Space complexity: .