当前位置:网站首页>【二叉树-中等】2265. 统计值等于子树平均值的节点数
【二叉树-中等】2265. 统计值等于子树平均值的节点数
2022-08-10 01:52:00 【菜菜2022】
【题目】
【代码】
【方法1】
使用先序遍历+哈希,占用较高的额外空间
# 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 visit(self,root):
if not root:
return
if root.val not in self.cnt:
self.cnt[root]=[]
if root.left:
self.cnt[root].append(root.left)
if root.right:
self.cnt[root].append(root.right)
self.visit(root.left)
self.visit(root.right)
def averageOfSubtree(self, root: Optional[TreeNode]) -> int:
self.cnt={
}
ans=0
self.visit(root)
# print(self.cnt)
for key in self.cnt:
temp_list=self.cnt[key]
for item in temp_list:
if item in self.cnt:
temp_list+=self.cnt[item]
temp_list=[item.val for item in temp_list]
temp_sum=0
if len(temp_list):
temp_sum=sum(temp_list)
temp_sum+=key.val
if key.val==(temp_sum//(1+len(temp_list))):
ans+=1
return ans
【方法2】
使用后序遍历
# 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 averageOfSubtree(self, root: Optional[TreeNode]) -> int:
# 统计每个子树的总值和个数
ans = 0
def dfs(root):
nonlocal ans
if root is None:
return 0,0
l,countLeft = dfs(root.left)
r,countRight = dfs(root.right)
if root.val == (root.val+l+r)//(countRight+countLeft+1):
ans += 1
return root.val+l+r ,countRight+countLeft+1
dfs(root)
return ans
边栏推荐
猜你喜欢
In automated testing, test data is separated from scripts and parameterized methods
odoo公用变量或数组的使用
Visual low-code system practice based on design draft identification
基于C51的中断控制
OpenSSF的开源软件风险评估工具:Scorecards
2022杭电多校联赛第七场 题解
Unity3D创建道路插件EasyRoads的使用
Problems and solutions related to Chinese character set in file operations in ABAP
多线程之自定义线程池
SQL注入的order by ,limit与宽字节注入
随机推荐
力扣每日一题-第51天-744. 寻找比目标字母大的最小字母
Under pressure, there must be cowards
2022杭电多校联赛第七场 题解
高压之下,必有懦夫
高并发+海量数据下如何实现系统解耦?【下】
sqlmap dolog外带数据
C# 单例模式
谷歌翻译器-谷歌翻译器软件批量自动翻译
首次在我们的centos登录我们的Mysql
hopscotch game
Nacos源码分析专题(五)-Nacos小结
微生物是如何影响身体健康的
OpenCV图像处理学习一,加载显示修改保存图像相关函数
openpose脚部标注问题梳理
2022 Top Net Cup Quals Reverse Partial writeup
【UNR #6 B】机器人表演(DP)
Database management tool: dynamic read-write separation
[Syntax sugar] About the mapping of category strings to category numeric ids
Initial attempt at UI traversal
odoo公用变量或数组的使用