## 题目描述：

LeetCode 652. 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.

## Python代码：

``````# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
def findDuplicateSubtrees(self, root):
"""
:type root: TreeNode
:rtype: List[TreeNode]
"""
treeMap = collections.defaultdict(list)
def flattenTree(root):
if not root:
ans = '#'
else:
ans = '%s(%s,%s)' % (root.val, flattenTree(root.left), flattenTree(root.right))
treeMap[ans].append(root)
return ans
flattenTree(root)
return [v[0] for v in treeMap.values() if len(v) > 1]
``````

Pingbacks已关闭。