# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
递归实现:
# 递归
def isSameTree2(self, p: TreeNode, q: TreeNode) -> bool:
if not p and not q: return True
if p and q and p.val==q.val:
return self.isSameTree(p.left,q.left) and self.isSameTree(p.rihgt,q.right)
迭代实现:
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
stack=[(p,q)]
while stack:
a,b = stack.pop()
if not a and not b:
continue
if a and b and a.val==b.val:
stack.append((a.right,b.right))
stack.append((a.left,b.left))
else:
return False
return True