leetcode-508 Most Frequent Subtree Sum

Posted on 2020-11-07 17:17  actor_spider  阅读(72)  评论(0)    收藏  举报

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.

输入输出实例:

input:[5, 2, -3]

output: [2, -3, 4]

代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def getData(self, root):
        if root == None:
            return 0
        else:
            root.val = root.val + self.getData(root.left) + self.getData(root.right)
            if root.val in self.dic:
                self.dic[root.val] += 1
            else:
                self.dic[root.val] = 1
            return root.val  
        
    def findFrequentTreeSum(self, root: TreeNode) -> List[int]:
        if root == None:return []
        self.dic = {}
        self.getData(root)
        data = sorted(self.dic.items(),key = lambda x:x[1], reverse = True)
        
        maxTime = data[0][1]
        result = []
        for i in range(len(data)):
            if maxTime == data[i][1]:
                result.append(data[i][0])
        return result

 

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3