diff --git a/0572_subtree-of-another-tree/README.md b/0572_subtree-of-another-tree/README.md new file mode 100644 index 0000000..2a4f10c --- /dev/null +++ b/0572_subtree-of-another-tree/README.md @@ -0,0 +1,28 @@ +Given the roots of two binary trees `root` and `subRoot`, return `true` if there is a subtree of `root` with the same structure and node values of `subRoot` and `false` otherwise. + +A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/04/28/subtree1-tree.jpg) + + Input: root = [3,4,5,1,2], subRoot = [4,1,2] + Output: true + + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/04/28/subtree2-tree.jpg) + + Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2] + Output: false + + +**Constraints:** + +* The number of nodes in the `root` tree is in the range `[1, 2000]`. +* The number of nodes in the `subRoot` tree is in the range `[1, 1000]`. +* `-104 <= root.val <= 104` +* `-104 <= subRoot.val <= 104` + +https://leetcode.com/problems/subtree-of-another-tree \ No newline at end of file diff --git a/0572_subtree-of-another-tree/python3/solution.py b/0572_subtree-of-another-tree/python3/solution.py new file mode 100644 index 0000000..afe8bba --- /dev/null +++ b/0572_subtree-of-another-tree/python3/solution.py @@ -0,0 +1,26 @@ +# 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)