leetcode/0572_subtree-of-another-tree/python3/solution.py

27 lines
858 B
Python

# 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:
if subRoot is None:
return True
elif root is None:
return False
if self.isSameTree(root, subRoot):
return True
return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)
def isSameTree(self, a, b):
if a is None and b is None:
return True
elif a is None or b is None or a.val != b.val:
return False
return self.isSameTree(a.left, b.left) and self.isSameTree(a.right, b.right)