【二叉树-中等】2265. 统计值等于子树平均值的节点数

这篇博客介绍了两种方法来计算二叉树中所有子树的平均值,并找出具有该平均值的子树数量。方法一采用先序遍历结合哈希表,方法二利用后序遍历。这两种方法分别实现了对树节点的遍历,计算每个子树的节点值之和与节点数量,进而找到满足条件的子树。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【题目】
【代码】
【方法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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值