【题目】
【代码】
【方法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
二叉树子树平均值计算:先序遍历与后序遍历方法
这篇博客介绍了两种方法来计算二叉树中所有子树的平均值,并找出具有该平均值的子树数量。方法一采用先序遍历结合哈希表,方法二利用后序遍历。这两种方法分别实现了对树节点的遍历,计算每个子树的节点值之和与节点数量,进而找到满足条件的子树。
172万+

被折叠的 条评论
为什么被折叠?



