Binary Search Tree : Lowest Common Ancestor

  • + 4 comments

    your logic is incorrect after.....

    if(root -> data < v1)

    lca(root -> right , v1 , v2);

    else

    lca(root -> left , v1 , v2);

    return safe; } In this case you are not checking v2. you may lose the trail of v2 while traversing. In your decision logic your root depends on v1 as well as v2...... go for the simple code...

    node * lca(node * root, int v1,int v2)

    {

    if(v1<root->data && v2<root->data)
        root=lca(root->left,v1,v2);
    else if(v1>root->data && v2>root->data)
        root=lca(root->right,v1,v2);
    return root;
    

    }