Lowest common ancestor in binary search tree

Image result for binary search tree images

    In the above tree if you see node 1 the ancestors(nodes which are higher in hierarchy) are 3, 8. And for 4 the ancestors are 3,6 and 8. So the lowest(close to both nodes) common ancestor of 1 and 4 is 3.

    Now for a given nodes v1 and v2 we have to find the lowest common ancestor of both nodes.

    In binary search tree if a given value say v1 is lesser than the present node then it is definitely lies in the left subtree. Similarly if the given value is greater than the present node then it lies in the right subtree. Using this property we will solve the example problem as shown below.


Solving the problem:
We will follow the below steps to find the lca of 1 and 4.

1. We will be starting with the root node which is 8. Both 3 and 4 is less than 8, so we will go to left subtree of 8.
2. current node is 3. Here 1 is less than 3 but 4 is greater than 3. This is the key point of the problem. At node 3 one value is less other value is greater. Which means one will be present in left subtree and other value will present in right subtree. So hereafter there is no possibility for them to have common ancestors as both of them are travelling in different directions.

 Algorithm:
1. Visit the  node (root node initially). 
2. If both the given values are less than the node visit the left subtree and continue step 1
3. If both the given values are greater than the node visit the right subtree and continue step 1.
4. else return node.

Code:
static Node lca(Node root,int v1,int v2)
    {
        while(true){
            if( v1 > root.data && v2 > root.data )
                root = root.right;
            else if( v1 < root.data && v2 < root.data )
                root = root.left;
            else
                break;
        }
  
        return root;
    }


     

Comments

Popular posts from this blog

Tree traversals - Inorder Traversal

Binary Search tree (Insertion)

Stack implementation using array