Count Nodes Equal to Average of Subtree

medium tree dfs

Problem

Given the root of a binary tree, count how many nodes have a value equal to the average of all values in that node's subtree (the node itself plus every descendant). The average is computed with integer division — divide the subtree's total sum by the number of nodes in the subtree and drop any fractional part.

Inputtree (level-order) = [4, 8, 5, 0, 1, _, 6]
Output5
Root 4: subtree sum 24, size 6, avg 4 → match. Node 5: sum 11, size 2, avg 5 → match. The three leaves 0, 1, 6 each equal their own average. Node 8: sum 9, size 3, avg 3 → no. So 5 nodes qualify.

def average_of_subtree(root):
    count = 0
    def dfs(n):
        nonlocal count
        if not n: return (0, 0)
        ls, lc = dfs(n.left)
        rs, rc = dfs(n.right)
        s = ls + rs + n.val
        c = lc + rc + 1
        if n.val == s // c: count += 1
        return (s, c)
    dfs(root)
    return count
function averageOfSubtree(root) {
  let count = 0;
  function dfs(n) {
    if (!n) return [0, 0];
    const [ls, lc] = dfs(n.left);
    const [rs, rc] = dfs(n.right);
    const s = ls + rs + n.val;
    const c = lc + rc + 1;
    if (n.val === Math.floor(s / c)) count++;
    return [s, c];
  }
  dfs(root);
  return count;
}
class Solution {
    int count;
    public int averageOfSubtree(TreeNode root) {
        count = 0;
        dfs(root);
        return count;
    }
    private int[] dfs(TreeNode n) {
        if (n == null) return new int[]{0, 0};
        int[] L = dfs(n.left);
        int[] R = dfs(n.right);
        int s = L[0] + R[0] + n.val;
        int c = L[1] + R[1] + 1;
        if (n.val == s / c) count++;
        return new int[]{s, c};
    }
}
int count_;
pair<int, int> dfs(TreeNode* n) {
    if (!n) return {0, 0};
    auto L = dfs(n->left);
    auto R = dfs(n->right);
    int s = L.first + R.first + n->val;
    int c = L.second + R.second + 1;
    if (n->val == s / c) count_++;
    return {s, c};
}
int averageOfSubtree(TreeNode* root) {
    count_ = 0;
    dfs(root);
    return count_;
}
Time: O(n) Space: O(h)