: 2265. Count Nodes Equal to Average of Subtree
: 给你一个二元树
: 回传"所有结点等于该结点子树的平均值(无条件舍去)"的数量
: 直接举例比较清楚
: https://assets.leetcode.com/uploads/2022/03/15/image-20220315203925-1.png
: Input: root = [4,8,5,0,1,null,6]
: Output: 5
: 对4来说 (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4
: 对5来说 (5 + 6) / 2 = 11 / 2 = 5
: 对0来说 0 / 1 = 0
: 对1来说 1 / 1 = 1
: 对6来说 6 / 1 = 6
愚笨如我只想得到递回,不知道有没有藏什么数学特性
========== Python
from collections import defaultdict
class Solution:
def averageOfSubtree(self, root: Optional[TreeNode]) -> int:
if (root == None):
return 0
self.subSum = defaultdict(int)
self.subCount = defaultdict(int)
self.count = 0
self.cal_avg(root)
return self.count
def cal_avg(self, node):
if (node == None):
return
elif (node.left == None and node.right == None):
self.subSum[node] = node.val
self.subCount[node] = 1
self.count += 1
else:
self.cal_avg(node.left)
self.cal_avg(node.right)
self.subSum[node] = node.val + self.subSum[node.left] +
self.subSum[node.right]
self.subCount[node] = self.subCount[node.left] +
self.subCount[node.right] + 1
if (node.val == (self.subSum[node] // self.subCount[node])):
self.count += 1
========== C++
class Solution {
private:
int count = 0;
unordered_map<TreeNode*, int> subSum;
unordered_map<TreeNode*, int> subCount;
public:
int averageOfSubtree(TreeNode* root) {
calAverage(root);
return count;
}
void calAverage(TreeNode* node)
{
if (node == nullptr) return ;
if (node->left == nullptr && node->right == nullptr)
{
subSum[node] = node->val;
subCount[node] = 1;
count++;
return;
}
else
{
calAverage(node->left);
calAverage(node->right);
subSum[node] = node->val + subSum[node->right] +
subSum[node->left];
subCount[node] = 1 + subCount[node->right] + subCount[node->left];
if (node->val == (subSum[node] / subCount[node])) count++;
}
}
};