HanchengZhao / algorithm-notes

0 stars 0 forks source link

652. Find Duplicate Subtrees #13

Open HanchengZhao opened 6 years ago

HanchengZhao commented 6 years ago

652. Find Duplicate Subtrees

HanchengZhao commented 6 years ago
from collections import defaultdict
class Solution(object):
    def findDuplicateSubtrees(self, root):
        """
        :type root: TreeNode
        :rtype: List[TreeNode]
        """
        def tupify(root):
            if root:
                sub = root.val, tupify(root.left), tupify(root.right)
                subtrees[sub].append(root)
                return sub
        subtrees = defaultdict(list)
        tupify(root)
        res = []
        for i in subtrees.values():
            if len(i) > 1:
                res.append(i[0])
        return res
        # return [node[0] for i in subtrees.values() if node[1:]]

'''
1.save the subtree structure as a tuple 2.build a dictionary to make the structure as a key and node as value

it takes O(n) time complexity and O(n) space '''