Count Nodes Equal to Average of Subtree
Medium
Topics
For each node, consider the subtree rooted at it. Count the nodes whose value equals the average (rounded down) of all values in that subtree.
Example 1
null marks a missing child.Input: root = [4,8,5,0,1,null,6] Output: 5
Example 2
Input: root = [1] Output: 1
Constraints
- 1 <= number of nodes <= 1000
- 0 <= Node.val <= 1000
Editorial — intuition, approach, complexity and pitfalls
Intuition
Each node needs the average of its own subtree, which requires both the subtree's sum and its node count. Computing those separately per node re-walks the tree repeatedly and is O(n^2) on a path.
One post-order pass gives both: a node's sum and count are its children's sums and counts plus itself. So have the recursion return a pair and accumulate the answer on the side — the same "return one thing up, collect another" shape as the tilt problem, but the returned value is a tuple rather than a single number.
The comparison uses integer division, because the problem defines the average as rounded down. sum // count == node.val is the test, and using floating-point division would make a node with average 4.5 and value 4 compare unequal when the problem says it should match.
Approach
- Post-order DFS returning
(sum, count); a null node returns(0, 0). - Combine both children with the node itself.
- Increment the answer when
sum // count == node.val.
Dry Run
tree 4
/ \
8 5
/ \ \
0 1 6
leaf 0: (0,1) avg 0 == 0 count 1
leaf 1: (1,1) avg 1 == 1 count 2
node 8: (0+1+8, 1+1+1) = (9,3) avg 9//3 = 3 != 8
leaf 6: (6,1) avg 6 == 6 count 3
node 5: (6+5, 1+1) = (11,2) avg 11//2 = 5 == 5 count 4
root 4: (9+11+4, 3+2+1) = (24,6) avg 24//6 = 4 == 4 count 5
answer 5Note node 5: the true average is 5.5, and floor division makes it 5, which matches the node. Floating-point division would have missed it.
Complexity
- Time — O(n): each node visited once. Against O(n^2) for recomputing subtree sums per node.
- Space — O(h): the recursion stack.
Common Pitfalls
- Using true division instead of floor division. The problem rounds the average down, and node 5 above is exactly the case that exposes the difference.
- Returning only the sum and recomputing counts separately, which costs a second traversal.
- Forgetting the node itself in either the sum or the count.
- Returning
(0, 1)for a null node, which inflates every count by the number of absent children. - Every leaf counts — its subtree is itself, so its average always equals its value. Expect the answer to be at least the leaf count.
Full Solution — all languages
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):
self.cnt = 0
def dfs(node):
if not node: return (0, 0)
ls, lc = dfs(node.left); rs, rc = dfs(node.right)
s = ls + rs + node.val; c = lc + rc + 1
if s // c == node.val: self.cnt += 1
return (s, c)
dfs(root)
return self.cntimport java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public int averageOfSubtree(TreeNode root) {
cnt = 0;
dfs(root);
return cnt;
}
int cnt;
private int[] dfs(TreeNode node) {
if (node == null) return new int[]{0, 0};
int[] l = dfs(node.left), r = dfs(node.right);
int s = l[0] + r[0] + node.val, c = l[1] + r[1] + 1;
if (s / c == node.val) cnt++;
return new int[]{s, c};
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: int averageOfSubtree(TreeNode* root) {
int cnt = 0;
function<pair<int,int>(TreeNode*)> dfs = [&](TreeNode* node) -> pair<int,int> {
if (!node) return {
0, 0
};
auto l = dfs(node->left);
auto r = dfs(node->right);
int s = l.first + r.first + node->val, c = l.second + r.second + 1;
if (s / c == node->val) cnt++;
return {
s, c
};
};
dfs(root);
return cnt;
}
};/**
* Tree node shape: { val, left, right }
* @param {TreeNode} root
* @return {number}
*/ var averageOfSubtree = function(root) {
let cnt = 0;
const dfs = (node) => {
if (!node) return [0, 0];
const l = dfs(node.left), r = dfs(node.right);
const s = l[0] + r[0] + node.val, c = l[1] + r[1] + 1;
if (Math.floor(s / c) === node.val) cnt++;
return [s, c];
};
dfs(root);
return cnt;
};