Graph Theory37 sections · 1633 units
Open in Course

DP Method - Implementation

Recursive DFS

Here is the solution:

diameter = 0

function dfs(node, parent, adj):
    max1 = 0
    max2 = 0
    for child in adj[node]:
        if child == parent:
            continue
        childHeight = dfs(child, node, adj) + 1
        if childHeight > max1:
            max2 = max1
            max1 = childHeight
        else if childHeight > max2:
            max2 = childHeight
    diameter = max(diameter, max1 + max2)
    return max1

This tracks the top two depths and updates the global diameter.

This runs in O(n)O(n) time and uses O(n)O(n) space.