题目描述
链接:https://leetcode-cn.com/problems/same-tree/
解题思路:
通过递归比较左右子树。
1.若比完都空,则完全相同。
2.若仅一个空,则一定不相同。
3.若结点的值不相同,则一定不同。
代码
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
if p.val!=q.val:
return False
return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)