Home » Data Structure & Algorithms » Lowest Common Ancestor in a BST

Lowest Common Ancestor in a BST

 

Question :

WAP to find the lowest common ancestor of two given nodes  a binary search Tree.

Let T1 be a rooted tree. The lowest common ancestor between two nodes n1 and n2 is defined as the lowest node in T1  that has both n1 and n2 as descendants.

 

In the above Tree ,LowestCommonAncestor(LCA) of Node 4 and Node 7 in BST is Node 6.Similary LowestCommonAncestor of Node 1 and Node 14 in BST is Node 8

Algorithm :

The problem is solved in recursive way.

Step 1 : If the node is null ,return null.

Step 2 : If  both data1 and data2 are equal to root ,then return root.data1 and data2 are two node values for which we are finding LCA.

Step 3 : If  both data1 and data2 are equal to root ,then traverse left sub tree, as LCA lies in left sub tree.

Step 4 : If  both data1 and data2 are equal to root ,then traverse right sub tree, as LCA lies in right sub tree.

Program :

 
 


Leave a comment

Your email address will not be published. Required fields are marked *

17 + 17 =