I am having a tough time understanding Tarjan's lowest common ancestor algorithm. Can somebody explain it with an example?
I am stuck after the DFS search, what exactly does the algorithm do?
In graph theory and computer science, the lowest common ancestor (LCA) (also called least common ancestor) of two nodes v and w in a tree or directed acyclic graph (DAG) T is the lowest (i.e. deepest) node that has both v and w as descendants, where we define each node to be a descendant of itself (so if v has a direct ...
Follow the given steps to solve the problem: Create a recursive function that takes a node and the two values n1 and n2. If the value of the current node is less than both n1 and n2, then LCA lies in the right subtree. Call the recursive function for the right subtree.
Since we have a path between any two nodes in the binary tree, then we have a path between any node and the root node. Thus, for any two nodes in a binary tree, the root is a common ancestor.
My explanation will be based on the wikipedia link posted above :).
I assumed that you already know about the union disjoint structure using in the algorithm. (If not please read about it, you can find it in "Introduction to Algorithm").
The basic idea is every times the algorithm visit a node x
, the ancestor of all its descendants will be that node x
.
So to find a Least common ancestor (LCA) r
of two nodes (u,v)
, there will be two cases:
Node u
is a child of node v
(vice versa), this case is obvious.
Node u
is ith branch and v
is the jth branch (i < j) of node r
, so after visit node u
, the algorithm backtrack to node r
, which is the ancestor of the two nodes, mark the ancestor of node u
as r
and go to visit node v
.
At the moment it visit node v
, as u
is already marked as visited (black), so the answer will be r
. Hope you get it!
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