# Leetcode: Find Duplicate Subtrees

Find Duplicate Subtrees

Similar Problems:

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.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.

```// Blog link: https://code.dennyzhang.com/find-duplicate-subtrees
// Basic Ideas: hashmap
// Encode binarytree to string
// Complexity: Time O(n), Space O(n)
/**
* Definition for a binary tree node.
* type TreeNode struct {
*     Val int
*     Left *TreeNode
*     Right *TreeNode
* }
*/
func findDuplicateSubtrees(root *TreeNode) []*TreeNode {
m := map[string]int{}
res := []*TreeNode{}
postTree(root, m, &res)
return res
}

func postTree(root *TreeNode, m map[string]int, res *[]*TreeNode) string {
if root == nil { return "#" }
l, r := postTree(root.Left, m, res), postTree(root.Right, m, res)
v := fmt.Sprintf("%s,%s,%d", l, r, root.Val)
if m[v] == 1 { *res = append(*res, root) }
m[v]++
return v
}
```

Share It, If You Like It.