Easy understanding recursive solution


  • 0
    R
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 
    {
        if (!root || !p || !q)
            return NULL;
            
        if (q->val < root->val && p->val < root->val) //p, q in the left
            return lowestCommonAncestor(root->left, p, q);
        else if (q->val > root->val && p->val > root->val) // p, q in the right
            return lowestCommonAncestor(root->right, p, q);
        else // if q, p is not in the same left or right tree, return current node
            return root;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.