- 另一棵树的子树
# 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 isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
#判断是否是子树,主要分为两步:根节点的判断,树形状的判断
def hasSameTree(tmpRoot, tmpSubRoot):
if not tmpRoot and not tmpSubRoot:
return True
if not tmpRoot or not tmpSubRoot:
return False
if tmpRoot.val == tmpSubRoot.val:
return hasSameTree(tmpRoot.left, tmpSubRoot.left) and hasSameTree(tmpRoot.right, tmpSubRoot.right)
return False
if root:
if hasSameTree(root, subRoot):
return True
return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)
return False