Simple Recursive Python Solution with brief explaination

  • 0

    Trees are not equal has 3 conditions:

    1. One of the tree is empty while another is not

    2. Two root node has different value

    3. Left or right subtree are not equal

       class Solution:
       # @param p, a tree node
       # @param q, a tree node
       # @return a boolean
       def isSameTree(self, p, q):
           if p == None and q == None: return True
           if p == None or  q == None: return False
           if p.val != q.val: return False
           return self.isSameTree(p.left, q.left) and self.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.