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 time and uses space.