Count Nodes Equal to Average of Subtree

Medium

Topics
TreeDFS

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

081456
equals its subtree average
A node counts when it equals the floor of its own subtree’s average, counting itself. Returning (sum, count) from a post-order pass answers every node in one traversal; every leaf trivially qualifies. 5 here.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [4,8,5,0,1,null,6]
Output: 5

Example 2

1
equals its subtree average
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

  1. Post-order DFS returning (sum, count); a null node returns (0, 0).
  2. Combine both children with the node itself.
  3. 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 5

Note 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.cnt
Asked at Snowflake
SensAI
Beta
Tap the mic to stop voice mode