LOWEST COMMON ANCESTOR IN BST

 PROBLEM => FIND THE LOWEST COMMON ANCESTOR OF TWO NODES (a & b) IN BINARY                                    SEARCH TREE


STEPS => 

1.Find whether these two nodes are present in bst.If not found then return NULL.

2.If both nodes are found then there are 4 possibilites =>

                1.root == a || root == b => return root

                2.a is found in left subtree and b is found in right subtree => return NULL from that subtree                           where we cant find both a & b

                3.if a and b are found in left/right subtree return root

node* lca(node* root,int a,int b){

    if (root == NULL) // root is NULL
    {
        return NULL;
    }

    if (root -> data == a || root -> data == b) // if found numbers at current node
    {
        return root;
    }

    node* left = lca(root->left,a,b); // find in left subtree
    node* right =lca(root->right,a,b); // find in right subtree
   

    if (left == NULL) // if ntg is found in left subtree
    {
        return right;
    }
    if (right == NULL) // if ntg is found in right subtree
    {
        return left;
    }
   
   
    return root; // if elements are found in right and leftside of root.
       
}

Comments

Popular posts from this blog

3 MAPPING TECHNIQUES

VIRTUAL MEMORY

ADJACENT MATRIX