Count Nodes Equal to Average of Subtree

MediumTreesdfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given the root of a binary tree of non-negative integers, count the nodes whose value equals the **average** of the values in their subtree. A node's subtree is the node plus all of its descendants. The average of k values is their sum divided by k, **rounded down** to an integer. Every leaf therefore always counts.

Examples

Input: root = [4,8,5,0,1,null,6]
Output: 5
Node 4: (4+8+5+0+1+6)/6 = 4. Node 5: (5+6)/2 = 5. Node 8: (8+0+1)/3 = 3, not counted. The three leaves count.
Input: root = [1]
Output: 1
A single leaf equals its own average.

Constraints

  • 1 <= number of nodes <= 1000
  • 0 <= Node.val <= 1000

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs problems