Created
November 11, 2023 05:39
-
-
Save braddotcoffee/3716ae36c6e03d958e7381f3292eb700 to your computer and use it in GitHub Desktop.
572. Subtree of Another Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 identical_tree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]): | |
if root is None or subRoot is None: | |
return root == subRoot | |
if root.val != subRoot.val: | |
return False | |
return ( | |
self.identical_tree(root.left, subRoot.left) | |
and self.identical_tree(root.right, subRoot.right) | |
) | |
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool: | |
if root is None or subRoot is None: | |
return root == subRoot | |
if root.val == subRoot.val: | |
is_identical = self.identical_tree(root, subRoot) | |
if is_identical: | |
return True | |
return ( | |
self.isSubtree(root.left, subRoot) | |
or self.isSubtree(root.right, subRoot) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment