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

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

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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值