Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if p == None and q == None:
return True
if p == None or q == None:
return False
stackA = [p]
stackB = [q]
while stackA and stackB:
nodeA = self.moveNext(stackA)
nodeB = self.moveNext(stackB)
if nodeA.val != nodeB.val:
return False
if stackA or stackB:
return False
return True
def moveNext(self, stack):
node = stack.pop()
if node.left or node.right:
if node.left == None:
node.left = TreeNode('#')
if node.right == None:
node.right = TreeNode('#')
stack.append(node.left)
stack.append(node.right)
return node
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if p == None and q == None:
return True
if p == None or q == None:
return False
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)