FunctionRacerProblemsRace

Nodes Equal to Subtree Average

MediumTreesPython, JavaScript, TypeScript, Java, C++

You are given the root of a binary tree. For each node, look at its subtree (the node and all its descendants). The node counts if its value equals the average of all values in its subtree rounded down (use //). Return how many nodes count. A leaf always counts.

Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.

Example 1

root [4,8,5,0,1,null,6]
returns 5

Counting nodes: 4 (avg 24//6), 5 (11//2), 0, 1, 6. The 8 has average 3, so it does not count: 5 in total.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Trees problems