# LeetCode Find Duplicate Subtrees

LeetCode Find Duplicate Subtrees

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.

```  1
/
2
```

``` 2
\
1```

```class Solution {
private:
string DFS(TreeNode* root, unordered_map<string, vector<TreeNode*>>& inorders) {
if (root == NULL)return "";
string left = DFS(root->left, inorders);
string right = DFS(root->right, inorders);
string cur = "(" + left + "," + to_string(root->val) + "," + right + ")";
inorders[cur].push_back(root);
return cur;
}
public:
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
unordered_map<string, vector<TreeNode*>> inorders;
DFS(root, inorders);
vector<TreeNode*> ans;
for (auto &it : inorders) {
if (it.second.size() > 1)
ans.push_back(it.second[0]);
}
return ans;
}
};
```