Simple java solution, easy understanding


  • 4
    Z

    public boolean isSameTree(TreeNode p, TreeNode q) {

        if(q==null && p==null){
            return true;
        }
        
        if((q==null && p!=null) || (q!=null && p==null)){
            return false;
        }
        
        if(p.val!=q.val){
            return false;
        }
        
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
        
        
        
    }

  • 0
    S

    The 'if((q==null && p!=null) || (q!=null && p==null)){ return false; }' logic could be simplify to 'if (q == null || p == null) { return false; }'

    Since you already checked that both of them cannot be null when reaching to this code; if either of them is null, the tree is not the same.


  • 0
    Z

    Yes, you are right! Thank you !


Log in to reply
 

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