Ctrl K

Nodes at Their Subtree Average

Medium
You are given the root of a binary tree. The subtree of a node is the node itself together with all of its descendants. Count how many nodes hold a value equal to the average of the values in their subtree. The average is an integer one: the sum divided by the number of nodes, rounded down.
Example 1
root=tree_node([6, 2, 9, None, 3, 7]) → 3

Root 6: (6 + 2 + 9 + 3 + 7) / 5 = 27 / 5, which rounds down to 5, so no. Node 2: (2 + 3) / 2 = 2, yes. Node 9: (9 + 7) / 2 = 8, no. The leaves 3 and 7 always match their own average. The answer is 3.

Example 2
root=tree_node([4, 4, 4, 4]) → 4

All values are equal, so every node matches the average of its subtree.

Example 3
root=tree_node([0, 1]) → 2

The root's average is (0 + 1) / 2, which rounds down to 0, and the leaf's is 1. Both nodes count.

Constraints
  • The tree has between 1 and 1000 nodes
  • 0 ≤ Node.val ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsIs It a Search Tree? MediumTwo Mixed-Up Nodes MediumAll Leaf Paths With a Given Total MediumTree Into a Right Chain MediumDigit Branch Totals Medium
loading Python…
Input
root=tree_node([6, 2, 9, None, 3, 7])
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 78 tests on the server, hidden ones included.