<span>leetcode-508 Most Frequent Subtree Sum</span>

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

 

全部评论

相关推荐

不愿透露姓名的神秘牛友
12-18 11:21
优秀的大熊猫在okr...:叫你朋友入职保安,你再去送外卖,一个从商,一个从政,你们两联手无敌了,睁开你的眼睛看看,现在是谁说了算(校长在背后瑟瑟发抖)
选实习,你更看重哪方面?
点赞 评论 收藏
分享
牛客78682892...:直接点还好,总比要了简历也不回的强
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务