class Solution: def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool: if not root: return False if self.match(root, subRoot): return True return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot) def match(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]): if not root and not subRoot: return True if not root or not subRoot: return False return ( root.val == subRoot.val) and self.match(root.left,subRoot.left) and self.match(root.right,subRoot.right)
|