Graph Theory37 sections · 1633 units
Open in Course

Finding a Centroid - Implementation

(Complete solution)

Here is the solution:

function find_centroid(n, adj)
    root := 1
    size := compute_sizes(root, -1, adj)
    current := root
    while true
        heavy := -1
        for child in adj[current]
            if not removed[child] and size[child] > n / 2 then
                heavy := child
                if heavy = -1 then
                    return current
    current := heavy

This finds one centroid. The tree is guaranteed to have at least one, so the algorithm always terminates.

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