<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

 

全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 17:37
点赞 评论 收藏
分享
05-26 22:25
门头沟学院 Java
Java小肖:不会是想叫你过去把你打一顿吧,哈哈哈
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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