当前位置:网站首页>【二叉树-中等】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
边栏推荐
- Teach you how to write performance test cases
- JCMsuite—单模光纤传播模式
- sqlmap dolog外带数据
- [QNX Hypervisor 2.2用户手册]10.14 smmu
- 程序员的专属浪漫——用3D Engine 5分钟实现烟花绽放效果
- Open3D 泊松盘网格采样
- hint: Updates were rejected because the tip of your current branch is behind hint: its remote counte
- [网鼎杯 2020 青龙组]AreUSerialz
- C# 单例模式
- idea 删除文件空行
猜你喜欢
【二叉树-中等】1379. 找出克隆二叉树中的相同节点
OpenCV图像处理学习四,像素的读写操作和图像反差函数操作
卷积神经网络识别验证码
进程管理和任务管理
Experimental support for decorators may change in future releases.Set the "experimentalDecorators" option in "tsconfig" or "jsconfig" to remove this warning
数据治理(五):元数据管理
【二叉树-中等】1104. 二叉树寻路
[网鼎杯 2020 青龙组]AreUSerialz
Fusion Compute网络虚拟化
Screen 拆分屏幕
随机推荐
【wpf】自定义事件总结(Action, EventHandler)
Go语言JSON文件的读写操作
【wpf】拖拽的简单实现
【QT】QT项目:自制Wireshark
元素的盒子模型+标签的尺寸大小和偏移量+获取页面滚动距离
2022强网杯 Quals Reverse 部分writeup
STM32F103驱动HCSR04超声波测距显示
FILE结构体在stdio.h头文件源码里的详细代码
【web渗透】SSRF漏洞超详细讲解
多线程之享元模式和final原理
空间复杂度为O(1)的归并排序
基于FTP协议实现文件上传与下载
OpenCV图像处理学习一,加载显示修改保存图像相关函数
Unity reports Unsafe code may only appear if compiling with /unsafe. Enable “Allow ‘unsafe’ code” in Pla
Fusion Compute网络虚拟化
Solve the problem of sed replacement text containing special characters such as "/" and "#"
.Net面试经验总结
RESOURCE_EXHAUSTED: etcdserver: mvcc: database space exceeded
hint: Updates were rejected because the tip of your current branch is behind hint: its remote counte
中文NER的SOTA:RICON