Quantcast
Channel: 书影 - Entries for the tag leetcode
Viewing all articles
Browse latest Browse all 559

[LeetCode]Find Duplicate Subtrees

$
0
0

题目描述:

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]

 


Viewing all articles
Browse latest Browse all 559

Trending Articles