Graph Theory37 sections · 1633 units
Open in Course

CSES 1131 Tree Diameter - Implementation

Pseudocode and code

Here is the solution:

function bfs(start, adj, n):
    dist = array of size n + 1, all -1
    dist[start] = 0
    queue = [start]
    farthest = start
    maxDist = 0

    for node in queue:
        for neighbor in adj[node]:
            if dist[neighbor] == -1:
                dist[neighbor] = dist[node] + 1
                queue.append(neighbor)
                if dist[neighbor] > maxDist:
                    maxDist = dist[neighbor]
                    farthest = neighbor

    return (farthest, maxDist)

function treeDiameter(adj, n):
    (u, _) = bfs(1, adj, n)
    (v, diameter) = bfs(u, adj, n)
    return diameter

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