My concise c++ solution


  • 0
    B

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
    if(root == NULL)
    {
    return NULL;
    }

        TreeNode* left = lowestCommonAncestor(root->left, p, q);
        TreeNode* right = lowestCommonAncestor(root->right, p, q);
        
        
        if(root == p || root == q)
        {
            return root;
        }
        
        if(left != NULL && right != NULL)
        {
            return root;
        }
        
        if(left != NULL && right == NULL)
        {
            return left;
        }
        
        if(left == NULL && right != NULL)
        {
            return right;
        }
        
        return NULL;
    }

Log in to reply
 

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