采用深度优先搜索的方式:
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if not p and not q: #两个树都为空
return True
elif not p or not q: #只有一个为空
return False
elif p.val != q.val: # 注意!!!
return False
else:
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
自己在写的时候,直接用p[i++] !=q[i++],错误之处:
1.首先树在取值的时候要采用.val去取值,感觉是因为树中存储不仅四value,还有left,right树
2.python没有i++ 操作,有 i +=1的写法
采用层次遍历
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if not p and not q:
return True
if not p or not q:
return False
queue1 = collections.deque([p])
queue2 = collections.deque([q])
while queue1 and queue2:
node1 = queue1.popleft()
node2 = queue2.popleft()
if node1.val != node2.val:
return False
left1, right1 = node1.left, node1.right
left2, right2 = node2.left, node2.right
if (not left1) ^ (not left2):
return False
if (not right1) ^ (not right2):
return False
if left1: #如果树左右不为空,则把它加入队列
queue1.append(left1)
if right1:
queue1.append(right1)
if left2:
queue2.append(left2)
if right2:
queue2.append(right2)
return not queue1 and not queue2