日野弥生:勉強しよう
LeetCode 100 - 相同的树
发表于2025年03月07日
递归解题,整体思路是先根遍历。
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
# 如果左右子树一个为空一个不为空,直接返回
if (not p and q) or (not q and p):
return False
# 都不为空,但是值不同
if (p and q and p.val != q.val):
return False
# 都为空返回
if not p and not q:
return True
left = self.isSameTree(p.left if p.left else None, q.left if q.left else None)
right = self.isSameTree(p.right if p.right else None, q.right if q.right else None)
# 左右子树都同时True
return left and right