Answer
See the explanation
Work Step by Step
Here's a Python algorithm to decide whether T2 is a subtree of T1:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_identical(root1, root2):
if root1 is None and root2 is None:
return True
if root1 is None or root2 is None:
return False
return (root1.val == root2.val and
is_identical(root1.left, root2.left) and
is_identical(root1.right, root2.right))
def is_subtree(T1, T2):
if T2 is None:
return True
if T1 is None:
return False
if is_identical(T1, T2):
return True
return is_subtree(T1.left, T2) or is_subtree(T1.right, T2)
# Example usage:
# T1 and T2 are instances of TreeNode class
# Call is_subtree(T1, T2) to check if T2 is a subtree of T1
```
Explanation:
- We define a `TreeNode` class to represent the nodes of the binary tree.
- The `is_identical` function checks if two trees rooted at `root1` and `root2` are identical.
- The `is_subtree` function recursively checks if `T2` is a subtree of `T1`.
- If `T2` is `None`, it is considered a subtree of any tree.
- If `T1` is `None`, `T2` cannot be a subtree.
- If the roots are identical, we recursively check if the left and right subtrees are identical.
- If `T2` is not found as a subtree at the current node, we recursively search in the left and right subtrees of `T1`.
- The algorithm has a time complexity of O(m * n), where m is the number of nodes in T1 and n is the number of nodes in T2.