If you want to be able to respond to distance(u, v) form requests quickly enough with quick preprocessing, you can use LCA . An LCA, or the lowest common ancestor, of the two vertices in the root tree is the vertex that is their ancestor of both, and which is the lowest among all their common ancestors. There is a not very complicated algorithm for searching LCA(u, v) in logarithmic time with n log n preprocessing time. I can describe it if necessary.
So, your problem can be solved as follows. First fix the root of your tree. Then do the above preprocessing to be able to find the LCA. Then, assuming that h[v] is the distance from v to the root (can be pre-calculated in linear time for all vertices), then distance(u, v) = h[u] + h[v] - 2 * h[LCA(u, v)] .
source share