652 Find Duplicate Subtrees
1
/ \
2 3
/ / \
4 2 4
/
4 2
/
4 4Last updated
1
/ \
2 3
/ / \
4 2 4
/
4 2
/
4 4Last updated
def findDuplicateSubtrees(self, root):
"""
:type root: TreeNode
:rtype: List[TreeNode]
"""
serials = collections.defaultdict(list)
def copyAllSubtrees(root):
if root is not None:
subtree = "%s,%s,%s" % (root.val, copyAllSubtrees(root.left), copyAllSubtrees(root.right))
serials[subtree].append(root)
return subtree
else:
return "#"
copyAllSubtrees(root)
return [roots[0] for serial, roots in serials.items() if len(roots) > 1]