Google News
logo
Data Structures Algorithms - Quiz(MCQ)
Consider we have a function, getLCA(), which returns us the Lowest Common Ancestor between 2 nodes of a tree. Using this getLCA() function, how can we calculate the distance between 2 nodes, given that distance from the root, to each node is calculated?
A)
dist(u) + dist(v)
B)
dist(u) + dist(v) - 2 * dist(getLCA(u, v))
C)
dist(u) + dist(v) - dist(getLCA(u, v))
D)
dist(u) + dist(v) + 2 * dist(getLCA(u, v))

Correct Answer :   dist(u) + dist(v) - 2 * dist(getLCA(u, v))


Explanation : The distance between 2 nodes, can be broken down into the sum of distances from the root, to each of the nodes. Observe, that in each of these paths, the path from the root to the LCA comes in each of them. So, this needs to be removed from the answer, and hence we get our formula in Option (B).

Advertisement