Why return(p == q) doesn't work?[Maybe a stupid Q, but I just want to know]

  • 0

    I have done this code and it was accepted, but I saw a very amazing answer in the Discuss, as:

    if( p == null || q == null )
    return p == q;

    then I was confused by the 'p == q', I submitted an answer like this:

    return ( p ==q );

    and I got Wrong Answer, input {0},{0} , output: false; Expected: true

    Oh... who can tell me how 'p == q' works? why it works in the first situation but not in mine?

  • 3

    I guess you are referring to this solution:

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

    Well in context of this solution, p==q would only check if either of them is null.

    If only one of them is null, it will return false.

    If both p and q are null, it will return true.

    However, if both are same trees, it will not return true.

    To sum up, "==" compares object references. It returns true if both of them point to the same object. In our case, p and q are "different" objects unless both of them are null.

    Hope this answered your question.

  • 0

    Thx a lot ~ I got it.

Log in to reply

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