# # 【LeetCode】652. Find Duplicate Subtrees 解题报告（Python）

## # 题目描述：

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.

## # 解题方法

``````# 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]
"""
res = []
m = collections.defaultdict(int)
self.helper(root, m, res)
return res

def helper(self, root, m, res):
if not root:
return '#'
path = str(root.val) + ',' + self.helper(root.left, m, res) + ',' + self.helper(root.right, m, res)
if m[path] == 1:
res.append(root)
m[path] += 1
return path
``````

## # 日期

2018 年 7 月 15 日 ———— 昨天火锅+啤酒，今天要加班了。。