2 Lines Java Code


  • 19
    M
    public class Solution {
        public boolean isSameTree(TreeNode p, TreeNode q) {
            if (p == null && q == null) return true;
            return p != null && q != null && p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        } }

  • 7
    S

    Same code for reference

    public boolean isSameTree(TreeNode p, TreeNode q) {
        // base case
        if(p==null || q==null) return p==null && q==null;
        // recursion
        return p.val==q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }

  • 1
    Y

    instead of p == null && q == null, we can just say p == q, a little bit easier


  • 0
    W

    @siyang3 as same as my code!


  • 0
    N

    1 line
    public boolean isSameTree(TreeNode p, TreeNode q) {
    return p != null && q != null ? p.val == q.val
    && isSameTree(p.left, q.left)
    && isSameTree(p.right, q.right) : p == null && q == null;
    }


Log in to reply
 

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