|
| 1 | +''' |
| 2 | +# 572. Subtree of Another Tree |
| 3 | +
|
| 4 | +## 1. Recursive |
| 5 | +use a recursive function to check if the two trees are identical. |
| 6 | +- if they are identical, return True. |
| 7 | +- if they are not identical, recursively check the left subtree and right subtree. |
| 8 | +
|
| 9 | +### base case |
| 10 | +- isSubtree |
| 11 | + - if the current tree is None, return False. |
| 12 | + - if the subRoot is None, return True. (empty tree is a subtree of any tree) |
| 13 | +- isIdentical |
| 14 | + - if both trees are None, return True. (they are identical) |
| 15 | + - if one of the trees is None, return False. |
| 16 | + - if the values of the current nodes are different, return False. |
| 17 | + - left subtree and right subtree's results are must be True. |
| 18 | +
|
| 19 | +## 2. Snapshot |
| 20 | +> reference: https://www.algodale.com/problems/subtree-of-another-tree/ |
| 21 | +
|
| 22 | +use a snapshot string of the preorder traversal to check if the subRoot is a subtree of the current tree. |
| 23 | +- if the subRoot is a subtree of the current tree, return True. |
| 24 | +- if the subRoot is not a subtree of the current tree, return False. |
| 25 | +''' |
| 26 | +class Solution: |
| 27 | + ''' |
| 28 | + 1. Recursive |
| 29 | + TC: O(n * m), m is the number of nodes in the subRoot. |
| 30 | + SC: O(n) (recursive stack space) |
| 31 | + ''' |
| 32 | + def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool: |
| 33 | + if not root: |
| 34 | + return False |
| 35 | + if not subRoot: |
| 36 | + return True |
| 37 | + |
| 38 | + if self.isIdentical(root, subRoot): |
| 39 | + return True |
| 40 | + |
| 41 | + return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot) |
| 42 | + |
| 43 | + def isIdentical(self, s: Optional[TreeNode], t: Optional[TreeNode]) -> bool: |
| 44 | + if not s and not t: |
| 45 | + return True |
| 46 | + if not s or not t: |
| 47 | + return False |
| 48 | + |
| 49 | + return s.val == t.val and self.isIdentical(s.left, t.left) and self.isIdentical(s.right, t.right) |
| 50 | + |
| 51 | + ''' |
| 52 | + 2. Snapshot |
| 53 | + TC: O(n + m), n is the number of nodes in the root, m is the number of nodes in the subRoot. |
| 54 | + SC: O(n + m) (recursive stack space) |
| 55 | + ''' |
| 56 | + def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool: |
| 57 | + def preorder(node): |
| 58 | + if not node: |
| 59 | + return '#' |
| 60 | + return f'({node.val},{preorder(node.left)},{preorder(node.right)})' |
| 61 | + |
| 62 | + return preorder(subRoot) in preorder(root) |
0 commit comments