> ## 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.

# Find Duplicate Subtrees Python Solution

> Tested Python solution for LeetCode 652 with 12 pytest cases. Generate a practice environment with lcpy.

LeetCode 652, [Medium](/catalog/medium). Topics: [Hash Table](/catalog/topics/hash-table), [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), [Binary Tree](/catalog/topics/binary-tree). [View on LeetCode](https://leetcode.com/problems/find-duplicate-subtrees/description/).

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

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

## Problem

Given the `root` of a binary tree, return all **duplicate subtrees**.

For each kind of duplicate subtrees, you only need to return the root node of any one **of them**.

Two trees are **duplicate** if they have the **same structure** with the **same node values**.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2020/08/16/e1.jpg)

```
Input: root = [1,2,3,4,null,2,4,null,null,4]
Output: [[2,4],[4]]
```

![Example 2](https://assets.leetcode.com/uploads/2020/08/16/e2.jpg)

```
Input: root = [2,1,1]
Output: [[1]]
```

![Example 3](https://assets.leetcode.com/uploads/2020/08/16/e33.jpg)

```
Input: root = [2,2,2,3,null,3,null]
Output: [[2,3],[3]]
```

### Constraints

* The number of the nodes in the tree will be in the range \[1, 5000]
* -200 \<= Node.val \<= 200

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import Counter

from leetcode_py import TreeNode


class Solution:
    # Time: O(n^2) worst case for string serializations
    # Space: O(n^2)
    def find_duplicate_subtrees(self, root: TreeNode[int] | None) -> list[TreeNode[int] | None]:
        counts: Counter[str] = Counter()
        result: list[TreeNode[int] | None] = []

        def serialize(node: TreeNode[int] | None) -> str:
            if node is None:
                return "#"
            key = f"{node.val},{serialize(node.left)},{serialize(node.right)}"
            counts[key] += 1
            if counts[key] == 2:
                result.append(node)
            return key

        serialize(root)
        return result
```

## Complexity

| Time | Space |
| - | - |
| O(n^2) worst case for string serializations | O(n^2) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.