I wonder why p != q does not work here

  • 1

    Hi all,
    Thanks for helping!

    I wrote this answer:

    def isSameTree(self, p, q):
            if p == None and q == None:
                return True
            elif p == None or q == None:
                return False
            elif p != q:
                return False
                left_ = self.isSameTree(p.left, q.left)
                right_ = self.isSameTree(p.right, q.right)
                return left_ and right_

    but oj shows my output is false while inputs are {0}, {0}, the expected result should be true.

    Then I read others answers, I found when I use : p.val != q.val
    The output is correct and has been accepted.
    I am confused by these two difference, can anyone explain this?
    Thanks a lot!!

  • 1

    p!=q condition checks whether the two object instances p and q are same, according to the function definition it is not the right condition to check for isSameTree function as one need to indeed check whether the two input trees p and q are structurally identical and the nodes have the same value.

Log in to reply

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