Dynamic Programming21 sections · 916 units
Open in Course

Tree Diameter - Implementation

Single DFS

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: O(n)O(n). You visit each node once. The trick is tracking the two longest paths to compute the diameter through that node. Space: O(n)O(n) for adjacency list plus recursion stack.

Time complexity: O(n)O(n).

Space complexity: O(n)O(n).