目录
题目
-
给你两棵二叉树的根节点 p 和 q ,编写一个函数来检验这两棵树是否相同。
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
题解
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
#空树返回true
if p is None and q is None:
return True
#两个树只有一个为空时
if (p == None and q != None) or (p != None and 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)
标签:None,right,return,相同,val,self,100,left
From: https://www.cnblogs.com/lushuang55/p/17879581.html