Iterative
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
que1, que2 = collections.deque([p]), collections.deque([q])
while(que1 and que2):
n1 = que1.popleft()
n2 = que2.popleft()
if n1 and n2:
if n1.val != n2.val:
return False
que1.append(n1.left)
que2.append(n2.left)
que1.append(n1.right)
que2.append(n2.right)
elif n1 != n2:
return False
return True
Recursion
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if p and q:
if p.val != q.val: return False
else: return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
return p == q