当前位置:网站首页>leetcode:508. 出现次数最多的子树元素和【dfs记录和】
leetcode:508. 出现次数最多的子树元素和【dfs记录和】
2022-04-22 11:36:00 【白速龙王的回眸】

分析
来个counter记录不同和的个数
然后dfs遍历左右求和,若为none返回0
否则返回左和+右和+本身,return前记录到count中
然后找到count的最大,并加入最大的key
ac code
# 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 findFrequentTreeSum(self, root: TreeNode) -> List[int]:
count = defaultdict(int)
def dfs(root):
if root is None:
return 0
leftSum = dfs(root.left)
rightSum = dfs(root.right)
thisSum = root.val + leftSum + rightSum
count[thisSum] += 1
return thisSum
dfs(root)
maxn = 0
for value in count.values():
maxn = max(maxn, value)
ans = []
for key in count.keys():
if count[key] == maxn:
ans.append(key)
return ans
总结
经典tree dfs
版权声明
本文为[白速龙王的回眸]所创,转载请带上原文链接,感谢
https://bridge-killer.blog.csdn.net/article/details/124341547
边栏推荐
- Finbi connects to native MySQL
- CrashSight 接入上报常见问题及解决方案
- 卷积神经网络
- MySQL learning notes
- Cloud native Virtualization: building edge computing instances based on kubevirt
- After installing yarn correctly, use yarn installation in vscode and report an error
- Category无法覆写系统方法?
- MySQL startup failure - reason why MySQL service cannot be started and its solution
- 创建对象内存分析与继承
- 从怎么阅读AWR报告说起
猜你喜欢

Redis 环境安装

postman接口测试工具视频教程,零基础入门到高手毕业

200. 岛屿数量

Mysql基本操作

Everyone is trying. Why don't you try

Yunrong technology joined the dragon dragon dragon community to help the digital transformation of the financial industry

vulnhub The Planets: Earth

MySQL startup failure: the MySQL service cannot be started. The service did not report any errors. Solution

11.(地图数据篇)OSM数据如何下载使用

在Docker环境上使用Debezium捕获PostgreSQL 14.2中的变更数据到Kafka
随机推荐
leetcode:347. Top k high frequency elements
怎么得到tuphub.today热榜和热度呢?
Synchronized lock and its expansion
redis 登录客户端命令
基于泰凌微TLSR825x的物联网解决方案之ibeacon开发总结
C语言小项目----> 推箱子
Fundamentals of machine learning
How to make the tab top by clicking on the tab bar
解决电脑连接正常,但浏览器无法打开网页的问题
PTC: major change in ESG product R & D of construction machinery
看的懂的C语言--字符串、转义字符、注释
If you are in Russia under "technology sanctions", gbase
MySQL 学习笔记
点击tab栏如何让tab置顶
APISIX jwt-auth 插件存在错误响应中泄露信息的风险公告(CVE-2022-29266)
Golang development: suggestions for go concurrency
MySQL prepare usage
MySQL installation summary
leetcode:347. 前 K 个高频元素
Graphic file system - I've seen the best article on file system