Binary Search Tree : Lowest Common Ancestor

  • + 2 comments

    I did it the same way, with a minor performance improvement: I arrange v1 and v2 so that I know which is larger:

    node* lca_(node* root, int a, int b)
    {
        if (b < root->data) {
            return lca_(root->left, a, b);
        }
        else if (a > root->data) {
            return lca_(root->right, a, b);
        }
        return root;
    }
    
    node* lca(node* root, int a, int b)
    {
        if (a < b) {
            return lca_(root, a, b);
        }
        return lca_(root, b, a);
    }