Given a general tree, I want the distance between two nodes v
and w
.
Wikipedia states the following:
Computation of lowest common ancestors may be useful, for instance, as part of a procedure for determining the distance between pairs of nodes in a tree: the distance from v to w can be computed as the distance from the root to v, plus the distance from the root to w, minus twice the distance from the root to their lowest common ancestor.
Let's say d(x)
denotes the distance of node x
from the root which we set to 1
. d(x,y)
denotes the distance between two vertices x
and y
. lca(x,y)
denotes the lowest common ancestor of vertex pair x
and y
.
Thus if we have 4
and 8
, lca(4,8) = 2
therefore, according to the description above, d(4,8) = d(4) + d(8) - 2 * d(lca(4,8)) = 2 + 3 - 2 * 1 = 3
. Great, that worked!
However, the case stated above seems to fail for the vertex pair (8,3)
(lca(8,3) = 2
) d(8,3) = d(8) + d(3) - 2 * d(2) = 3 + 1 - 2 * 1 = 2.
This is incorrect however, the distance d(8,3) = 4
as can be seen on the graph. The algorithm seems to fail for anything that crosses over the defined root.
What am I missing?
You missed that the lca(8,3) = 1
, and not = 2
. Hence the d(1) == 0
which makes it:
d(8,3) = d(8) + d(3) - 2 * d(1) = 3 + 1 - 2 * 0 = 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With