|
| 1 | +""" |
| 2 | +572. Subtree of Another Tree |
| 3 | +https://leetcode.com/problems/subtree-of-another-tree/description/ |
| 4 | +
|
| 5 | +Solution: |
| 6 | + This solution uses a depth-first search to find the subtree in the tree. |
| 7 | + We can use a recursive function to traverse the tree and compare the nodes. |
| 8 | + If the given node is identical to the subtree, we return True. |
| 9 | + Otherwise, we go to the left and right subtrees recursively. |
| 10 | + In this solution we use two helper functions: depth_first_search and is_identical. |
| 11 | +
|
| 12 | + Depth-first search: |
| 13 | + 1. Check if the root is None. |
| 14 | + 2. Check if the root is identical to the subtree. |
| 15 | + 3. Go to the left and right subtrees recursively. |
| 16 | +
|
| 17 | + Is identical: |
| 18 | + 1. Check if both nodes are None. |
| 19 | + 2. Check if one of the nodes is None. |
| 20 | + 3. Check if the values of the nodes are equal. |
| 21 | + 4. Compare the left and right subtrees recursively. |
| 22 | +
|
| 23 | +
|
| 24 | +Complexity analysis: |
| 25 | + Time complexity: O(n*m) |
| 26 | + Where n is the number of nodes in the tree and m is the number of nodes in the subtree. |
| 27 | + The depth-first search function has a time complexity of O(n). |
| 28 | + The is_identical function has a time complexity of O(m). |
| 29 | + Therefore, the overall time complexity is O(n*m). |
| 30 | +
|
| 31 | + Space complexity: O(m+n) |
| 32 | + Where n is the number of nodes in the tree and m is the number of nodes in the subtree. |
| 33 | + The space complexity is O(m+n) because of the recursive calls to the depth_first_search function |
| 34 | + and is_identical. |
| 35 | +""" |
| 36 | + |
| 37 | + |
| 38 | +from typing import Optional |
| 39 | + |
| 40 | + |
| 41 | +# Definition for a binary tree node. |
| 42 | +class TreeNode: |
| 43 | + def __init__(self, val=0, left=None, right=None): |
| 44 | + self.val = val |
| 45 | + self.left = left |
| 46 | + self.right = right |
| 47 | + |
| 48 | + |
| 49 | +class Solution: |
| 50 | + def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool: |
| 51 | + def depth_first_search(root): |
| 52 | + if root is None: |
| 53 | + return False |
| 54 | + |
| 55 | + if is_identical(root, subRoot): |
| 56 | + return True |
| 57 | + |
| 58 | + return depth_first_search(root.left) or depth_first_search(root.right) |
| 59 | + |
| 60 | + def is_identical(root1, root2): |
| 61 | + if root1 is None and root2 is None: |
| 62 | + return True |
| 63 | + if root1 is not None and root2 is None: |
| 64 | + return False |
| 65 | + if root1 is None and root2 is not None: |
| 66 | + return False |
| 67 | + if root1.val == root2.val: |
| 68 | + return ( |
| 69 | + is_identical(root1.left, root2.left) |
| 70 | + == is_identical(root1.right, root2.right) |
| 71 | + == True |
| 72 | + ) |
| 73 | + else: |
| 74 | + return False |
| 75 | + |
| 76 | + return depth_first_search(root) |
0 commit comments