Graph Theory37 sections · 1633 units
Open in Course

Fixed-Length Paths I - Implementation

(Complete solution)

Here is the solution:

function count_paths(node, adj, k)
    c := find_centroid(node, adj)
    result := count_through_centroid(c, adj, k)
    removed[c] := true
    for child in adj[c]
        if not removed[child] then
            result := result + count_paths(child, adj, k)
            return result

you will need to subtract same-subtree paths as well.

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