Binary Search Tree : Lowest Common Ancestor

  • + 0 comments

    C++ `14 Solution:

             
    //O(h) - h is height of the binary search tree ----> O(log(n))
    //Worst case (Skewed BST): Height h = n -- O(n). 
        Node *lca(Node *root, int v1,int v2) {
            if(root == nullptr) return root;
            while(root){
                if(v1 < root->data && v2 < root->data)
                    root= root->left;
                else if(v1 > root->data && v2 > root->data)
                    root = root->right;
                else
                    return root;
            }
            return root;
        }