Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

2265. Count Nodes Equal to Average of Subtree 🌟🌟

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:

Brute Force

Code

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;
    }
};

Optimized Solution

Code

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;
    }
};