> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Subtree of Another Tree Python Solution

> Tested Python solution for LeetCode 572 with 14 pytest cases. Generate a practice environment with lcpy.

LeetCode 572, Easy. Topics: Tree, Depth-First Search, String Matching, Binary Tree, Hash Function. [View on LeetCode](https://leetcode.com/problems/subtree-of-another-tree/description/).

Generate this problem as a practice environment: tested reference solution, 14 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 572   # by problem number
lcpy gen -s subtree_of_another_tree   # by problem name
```

## Problem

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.

### Examples

![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].
-10^4 \<= root.val \<= 10^4
-10^4 \<= subRoot.val \<= 10^4

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/subtree_of_another_tree/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/subtree_of_another_tree/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from leetcode_py import TreeNode


class Solution:
    # Time: O(m * n) - where m is nodes in root, n is nodes in sub_root
    # Space: O(h) - where h is height of root tree (recursion stack)
    def is_subtree(self, root: TreeNode[int] | None, sub_root: TreeNode[int] | None) -> bool:
        """
        Check if sub_root is a subtree of root.
        Uses DFS to check every node in root as potential subtree root.
        """
        if not sub_root:
            return True
        if not root:
            return False

        # Check if current root matches sub_root
        if self._is_same_tree(root, sub_root):
            return True

        # Recursively check left and right subtrees
        return self.is_subtree(root.left, sub_root) or self.is_subtree(root.right, sub_root)

    def _is_same_tree(self, p: TreeNode[int] | None, q: TreeNode[int] | None) -> bool:
        """Helper method to check if two trees are identical."""
        if not p and not q:
            return True
        if not p or not q:
            return False
        if p.val != q.val:
            return False

        return self._is_same_tree(p.left, q.left) and self._is_same_tree(p.right, q.right)
```

## Complexity

| Time                                                          | Space                                                   |
| ------------------------------------------------------------- | ------------------------------------------------------- |
| O(m \* n) - where m is nodes in root, n is nodes in sub\_root | O(h) - where h is height of root tree (recursion stack) |

## Tags

[Grind](/catalog/grind), [Blind 75](/catalog/blind-75), [NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode).
