Most Frequent Subtree Sum

利用分治法加上哈希表记录最高频即可

class Solution(object):
    def findFrequentTreeSum(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        store = collections.Counter()
        maxList = [0]
        self.helper(root, store, maxList)
        return [key for key, value in store.iteritems() if value == maxList[0]]

    def helper(self, root, store, maxList):
        if not root:
            return 0

        left, right = 0, 0
        if root.left:
            left = self.helper(root.left, store, maxList)
        if root.right:
            right = self.helper(root.right, store, maxList)
        store[left + right + root.val] += 1
        maxList[0] = max(maxList[0], store[left + right + root.val])
        return left + right + root.val

results matching ""

    No results matching ""