当前位置:网站首页>【二叉树-中等】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
边栏推荐
- Sikuli's Automated Testing Technology Based on Pattern Recognition
- web开发概述
- Chip Information|Semiconductor revenue growth expected to slow to 7%, Bluetooth chip demand still growing steadily
- Maya制作赛博朋克机器人模型
- 桌面云组件介绍与安装
- 在蓝图中给组件动态加子Actor组件
- 别再用 offset 和 limit 分页了,性能太差!
- C# 单例模式
- 实操|风控模型中常用的这三种预测方法与多分类场景的实现
- hopscotch game
猜你喜欢
随机推荐
数据库治理利器:动态读写分离
自动化测试中,测试数据与脚本分离以及参数化方法
ImportError: Unable to import required dependencies: numpy
牛客刷题——剑指offer(第四期)
hint: Updates were rejected because the tip of your current branch is behind hint: its remote counte
Research on Ethernet PHY Chip LAN8720A Chip
【SSRF漏洞】实战演示 超详细讲解
OpenCV图像处理学习三,Mat对象构造函数与常用方法
程序员的专属浪漫——用3D Engine 5分钟实现烟花绽放效果
mysql -sql编程
C# 单例模式
Fusion Compute网络虚拟化
Experimental support for decorators may change in future releases.Set the "experimentalDecorators" option in "tsconfig" or "jsconfig" to remove this warning
通关剑指 Offer——剑指 Offer II 012. 左右两边子数组的和相等
【论文笔记】基于深度学习的机器人抓取虚拟仿真实验教学系统
QT中,QTableWidget 使用示例详细说明
Golang nil的妙用
.Net interview experience summary
【wpf】拖拽的简单实现
墨西哥大众VW Mexico常见的几种label









