当前位置:网站首页>【二叉树-中等】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
边栏推荐
猜你喜欢
随机推荐
The flask to add and delete
In automated testing, test data is separated from scripts and parameterized methods
QT中,QTableWidget 使用示例详细说明
Interdepartmental Communication Skills
数组(一)
算法与语音对话方向面试题库
通关剑指 Offer——剑指 Offer II 012. 左右两边子数组的和相等
OpenCV图像处理学习四,像素的读写操作和图像反差函数操作
C# 单例模式
OpenSSF的开源软件风险评估工具:Scorecards
中级xss绕过【xss Game】
Open3D 泊松盘网格采样
HCIP——综合交换实验
实操|风控模型中常用的这三种预测方法与多分类场景的实现
《GB39732-2020》PDF下载
2022年8月1日-8月7日(本周10小时,合计1422小时,剩余8578小时)
Unity vertex animation
卷积神经网络识别验证码
Maya制作赛博朋克机器人模型
Unity image is blurry after using long image




![[论文阅读] Diverse Image-to-Image Translation via Disentangled Representations](/img/b8/891b8a8e7e70a1abd2016337ebc744.jpg)




