Count Nodes Equal to Average of Subtree (LeetCode 2265): Solution and Explanation

Medium
Tree
Depth First Search
Binary Tree

Given a binary tree, count the nodes whose value equals the rounded-down average of all values in their subtree, the node itself included.

Intuition

Computing each node's subtree sum from scratch visits the subtree again for every node, which is O(n^2) on a skewed tree.

But a subtree's sum is the left subtree's sum plus the right subtree's sum plus the node's value, and the same holds for the node count. So children can hand both numbers up to their parent.

A post-order DFS does exactly that: when a call returns, the parent already has everything it needs to compute its own average and compare it with its value.

Approach: Post-order DFS returning (sum, size)

  1. Define dfs(node) that returns (0, 0) for a null node.
  2. Recurse into the left and right children to get (ls, lc) and (rs, rc).
  3. Set total = ls + rs + node.val and size = lc + rc + 1.
  4. If total // size == node.val, add one to the counter.
  5. Return (total, size) to the parent, and after dfs(root) return the counter.

Step-by-step example

root = [4,8,5,0,1,null,6]
  1. Leaves 0 and 1 return (0, 1) and (1, 1). Each equals its own average, so count = 2.
  2. Node 8 gets 0 + 1 + 8 = 9 over 3 nodes. 9 // 3 = 3, not 8, so no count.
  3. Leaf 6 matches (count = 3). Node 5 gets 5 + 6 = 11 over 2 nodes, 11 // 2 = 5, a match (count = 4).
  4. The root gets 9 + 11 + 4 = 24 over 6 nodes, 24 // 6 = 4, a match (count = 5).
  5. Return 5.

Code: Python, Java, C++

1class Solution:
2    def averageOfSubtree(self, root: TreeNode) -> int:
3        count = 0
4
5        def dfs(node):
6            nonlocal count
7            if not node:
8                return 0, 0
9            ls, lc = dfs(node.left)
10            rs, rc = dfs(node.right)
11            total, size = ls + rs + node.val, lc + rc + 1
12            if total // size == node.val:
13                count += 1
14            return total, size
15
16        dfs(root)
17        return count
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Every node is visited once and does constant work.

Space

O(h)

The recursion stack holds one root-to-node path, where h is the tree height (up to n for a skewed tree).

Other approaches

Recompute each subtree (time O(n^2), space O(h))

For every node, run a separate traversal to sum and count its subtree. Easy to write, but subtrees get walked many times.

Iterative post-order with a stack (time O(n), space O(n))

Same idea with an explicit stack and a map from node to (sum, size). Avoids recursion depth limits at the cost of more bookkeeping.

Common mistakes

  • Using real division. The average is rounded down, so 11 / 2 must become 5, which matches node 5 in Example 1.
  • Forgetting to include the node itself in both the sum and the size.
  • Keeping the counter in a field without resetting it, so a reused Solution object carries the count from a previous tree.

Frequently asked questions

Why post-order and not pre-order?

A node's average depends on everything below it. Only after both children have returned does the node know its subtree sum and size.

Is a leaf always counted?

Yes. Its subtree is just itself, so the average is its own value.

Can the sum overflow?

No. At most 1000 nodes with values up to 1000 gives a sum of at most 10^6, which fits easily in a 32-bit integer.