Binary Search Tree : Lowest Common Ancestor

  • + 0 comments

    C++

    Node *lca(Node *root, int v1,int v2) {
    		// Write your code here.
            if(root==NULL)
                return NULL;
            if(root->data==v1 || root->data==v2)
                return root;
            Node* lca1=lca(root->left, v1, v2);
            Node* lca2=lca(root->right, v1, v2);
            if(lca1!=NULL &&lca2!=NULL)
                return root;
            else if(lca1!=NULL)
                return lca1;
            else
                return lca2;
        }