题目描述:
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.
题目大意:
寻找重复子树
解题思路:
将树序列化为字符串,利用Map<String, List>进行分类统计,将长度大于1的值列表中的首元素返回即可。
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]
本文链接:http://bookshadow.com/weblog/2017/07/30/leetcode-find-duplicate-subtrees/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。