# 652 Find Duplicate Subtrees

## 652. Find Duplicate Subtrees

## 1. Question

Given 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 same node values.

**Example 1:**

```
        1
       / \
      2   3
     /   / \
    4   2   4
       /
      4
```

The following are two duplicate subtrees:

```
      2
     /
    4
```

and

```
    4
```

Therefore, you need to return above trees' root in the form of a list.

## 2. Implementation

(1) Post order traversal + HashMap

```java
 public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
        List<TreeNode> res = new ArrayList<>();
        Map<String, Integer> map = new HashMap<>();

        postOrderTraversal(root, map, res);

        return res;
    }

    public String postOrderTraversal(TreeNode node, Map<String, Integer> map, List<TreeNode> res) {
        if (node == null) {
            return "#";
        }

        String leftCode = postOrderTraversal(node.left, map, res);
        String rightCode = postOrderTraversal(node.right, map, res);

        String curCode = node.val + leftCode + rightCode;

        if (map.getOrDefault(curCode, 0) == 1) {
            res.add(node);
        }
        map.put(curCode, map.getOrDefault(curCode, 0) + 1);
        return curCode;
    }
```

## 3. Time & Space Complexity

Post order traversal + HashMap: 时间复杂度: O(n), 空间复杂度: O(n)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://protegejj.gitbook.io/my-algorithm-summary/data-structure/tree/652-find-duplicate-subtrees.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
