Day4 -- Most Frequent Subtree Sum

Most Frequent Subtree Sum



Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order.

Examples 1
Input:

5
/ 2 -3
return [2, -3, 4], since all the values happen only once, return all of them in any order.
Examples 2
Input:

5
/ 2 -5
return [2], since 2 happens twice, however -5 only occur once.
Note: You may assume the sum of values in any subtree is in the range of 32-bit signed integer.

solution

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Time    : 2018/11/22 

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:

    def findFrequentTreeSum(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        map1 = {}

        def helper(root):
            if not root: return 0
            left_val = helper(root.left)
            right_val = helper(root.right)
            cur_sum = left_val + right_val + root.val
            print "cur_sum", cur_sum, left_val, right_val, root.val
            map1[cur_sum] = 1 if not map1.get(cur_sum) else map1[cur_sum] + 1
            return cur_sum

        helper(root)
        print "map", map1
        res = []
        value_list = [v for v in sorted(map1.values())]
        if value_list:
            max_fre = value_list[-1]
            res = [k for k, v in map1.items() if v == max_fre]
        return res


if __name__ == '__main__':
    node1 = TreeNode(2)
    node1.left = TreeNode(-5)
    node1.right = TreeNode(1)

    node3 = TreeNode(7)
    node3.left = TreeNode(9)
    node3.right = TreeNode(-7)

    node2 = TreeNode(8)
    node2.left = node1
    node2.right = node3

    s = Solution()
    res = s.findFrequentTreeSum(node2)
    print res

猜你喜欢

转载自www.cnblogs.com/khal-Cgg/p/10019463.html