LeetCode 508. Most Frequent Subtree Sum 解题报告(python)

508. Most Frequent Subtree Sum

  1. Most Frequent Subtree Sum python solution

题目描述

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.

在这里插入图片描述

解析

使用dfs求解,计算所有子树的node.value的值,将他们存在count数组中,统计和所出现的个数。

在输出的时候加上一个小判断,如果时出现次数最多的,就输出。如果不是出现次数最多的,就跳过!

class Solution:
    def findFrequentTreeSum(self, root: TreeNode) -> List[int]:
        if root is None: return []
        
        def dfs(node):
            if node is None : return 0
            s=node.val+dfs(node.left)+dfs(node.right)
            count[s]+=1
            return s
        
        count=collections.Counter()
        dfs(root)
        max_count=max(count.values())
        return [s for s in count if count[s]==max_count]

Reference

https://leetcode.com/problems/most-frequent-subtree-sum/discuss/98675/JavaC%2B%2BPython-DFS-Find-Subtree-Sum

发布了131 篇原创文章 · 获赞 6 · 访问量 6919

猜你喜欢

转载自blog.csdn.net/Orientliu96/article/details/104224310