Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tarjan's lowest common ancestor algorithm explanation

Tags:

algorithm

tree

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?

like image 477
happs Avatar asked Oct 09 '13 03:10

happs


People also ask

What is lowest common ancestor explain the algorithm?

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 ...

What approach will you follow to find the lowest common ancestor LCA of any two nodes in BST?

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.

How do you find the common parent of two nodes in a tree?

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.


1 Answers

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!

like image 176
Pham Trung Avatar answered Nov 15 '22 05:11

Pham Trung