Graph Theory37 sections · 1633 units
Open in Course

Tree Diameter - Implementation

(DP approach)

I'll show the DP approach. For each node, track max depth and update global diameter:

ans = 0

function dfs(u, p):
    m1 = 0
    m2 = 0
    for v in adj[u]:
        if v == p:
            continue
        d = dfs(v, u)
        if d > m1:
            m2 = m1
            m1 = d
        else if d > m2:
            m2 = d
    ans = max(ans, m1 + m2)
    return m1 + 1

dfs(1, 0)
print ans

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