3 lines Java solution


  • 14
    Y
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p==null && q==null) return true;
        if(p==null || q==null) return false;
        return (p.val==q.val) && isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }
    

    recursion


  • 0
    S

    I think you have to modify the 2nd if condition to be

    if((p==null || q==null) && !(p == null && q == null)) return false;

    Please correct me if I am wrong.


  • 0
    G

    this is already covered by the first statement : (p == null && q == null) can never be true on the second line because the second line states if(p==null && q==null) return true;


  • 0
    X

    Exactly what I did. :D


  • 0
    U

    @stuthi 2nd if is executed only if first if isn't ,thus !(p == null && q == null)) is extra.


Log in to reply
 

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