这个题目直接递归就行,难度不大,就是要考虑全面一些哦,这道题应该也是剑指offer的原题 ,复习一下,挺简单的,代码如下:
# 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: TreeNode, q: TreeNode) -> bool: if p==None and q==None: return True if p==None and q!=None or p!=None and q==None: return False bool_one=self.isSameTree(p.left,q.left) bool_two=self.isSameTree(p.right,q.right) if p.val==q.val: bool_three=True else: bool_three=False return bool_one and bool_two and bool_three
速度如下: