← Questions

Check that each tree node equals its subtree's average

0
MetaCodingLast asked Sep 2025

A coding interview question asked in Meta's AI-enabled coding round, last asked Sep 2025. It tests binary tree and dfs.

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

Interface

Unless you agree on a different interface with the interviewer, assume:

  • count_average_nodes(root: TreeNode | None) -> int — a node counts when node.val == subtree_sum // subtree_size.

Example

        4
       / \
      8   5
     / \    \
    0   1    6

count_average_nodes(root)   ->  5
  • Node 4: (4 + 8 + 5 + 0 + 1 + 6) / 6 = 4. Counts.
  • Node 8: (8 + 0 + 1) / 3 = 3. Does not count.
  • Node 5: (5 + 6) / 2 = 5.5, rounded down to 5. Counts.
  • Leaves 0, 1 and 6 always count.

With an exact average instead of rounding down, node 5 no longer counts and the answer is 4.

Constraints

  • Up to 10^5 nodes. Values may be negative.
  • O(n) time.

Clarifying questions

  • Does the subtree include the node itself?
  • Integer average rounded down, or exact? With negative values, does rounding go down or toward zero?
  • Return the count, the nodes, or a yes or no for "every node"?

What a strong answer covers

  • One post-order walk that returns (sum, size) for each subtree, compared at the node. O(n) time, O(h) stack.
  • Why recomputing the average from the top for each node is O(n²) on a skewed tree.
  • Exact comparison without floating point: sum == val * size.
  • Rounding of negative averages (// in Python floors, / in C++ and Java truncates).
  • Tests: an empty tree, one node, negative values, a skewed tree deep enough to need an iterative walk.

Follow-ups

  • Decide whether every node equals its subtree average (stop early on the first failure).
  • Use the average of the nodes strictly below each node, not including it.
  • Return the subtree with the highest average.

Where it's asked

  • Meta · AI-enabled coding · Last asked Sep 202560 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it

What it tests

binary tree · dfs

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding