Simple Java AC 0ms Solution


  • 3
    S
    public class Solution {
        public boolean isSameTree(TreeNode p, TreeNode q) {
            
           //need to check this first in order to avoid NullPointerException
            if(p == null && q == null)
                return true ; 
                
            if((p == null && q!=null) || (q==null && p!=null))
                return false ;
            
            if(p.val != q.val)
                return false ; 
           
            //if all fine so far, recurse
            return (isSameTree(p.left, q.left) && isSameTree(p.right, q.right)) ;
        }
    }

  • 1
    X

    Your second condition includes redundant condition and can be rewrite as following:

    else if (null == p || null == q)
    

    Full version below:

    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (null == p && null == q) // both null
            return true;
        else if (null == p || null == q) // one of them is null
            return false;
        else if (p.val != q.val) // both non-null, but value different
            return false;
        else // recursively check subtree
            return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
    

    or one line version (bad for reading, in case anybody find it useful):

    return null == p && null == q || !(null == p || null == q) && p.val == q.val && isSameTree(p.left, q.left) && 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.