<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

 

全部评论

相关推荐

产品经理傅立叶:1.建议把个人信息码一下 2.简历的排版还得优化一下,看上去有点乱,另外有一个实习经历实习时间好像多写了一个; 3.实习产出要量化
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务