My one line recursive solutions in 3 languages


  • 7

    I use syntactic sugar to combine stop condition and recursive call together.

    Java:

    return (p == null || q == null) ? p == q : p.val == q.val && this.isSameTree(p.left, q.left) && this.isSameTree(p.right, q.right);
    

    C++:

    return (p == NULL || q == NULL) ? p == q : p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
    

    Python:

    return p == q if p is None or q is None else p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

Log in to reply
 

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