508. Most Frequent Subtree Sum
- 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
本文解析了LeetCode上一道关于寻找二叉树中最频繁出现的子树和的问题。通过深度优先搜索(DFS)策略,文章详细介绍了如何计算每个节点的子树和,并统计这些和的频率。最终,算法返回出现频率最高的子树和值,为读者提供了清晰的代码实现和思路指导。
550

被折叠的 条评论
为什么被折叠?



