🎉 One-stop destination for all your technical interview Preparation 🎉
Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree.
Note:
class Solution {
private:
int getSum(TreeNode* root, int& count)
{
if (root == NULL) return 0;
count++;
int lSum = getSum(root->left, count);
int rSum = getSum(root->right, count);
return lSum + rSum + root->val;
}
public:
int ans = 0;
int averageOfSubtree(TreeNode* root)
{
if (root == NULL) return 0;
int count = 0;
int sum = getSum(root, count);
if (root->val == sum / count) ans++;
averageOfSubtree(root->left);
averageOfSubtree(root->right);
return ans;
}
};
class Solution {
int result;
pair<int, int> getSumAndCount(TreeNode* root)
{
if (root == nullptr) { return { 0, 0 }; }
auto [leftSum, leftCount] = getSumAndCount(root->left);
auto [rightSum, rightCount] = getSumAndCount(root->right);
int sum = leftSum + rightSum + root->val;
int count = leftCount + rightCount + 1;
int avg = sum / count;
if (avg == root->val) result++;
return { sum, count };
}
public:
int averageOfSubtree(TreeNode* root)
{
result = 0;
getSumAndCount(root);
return result;
}
};