Count Nodes Equal to Average of Subtree

Given the `root` of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree. The average of `n` elements is the sum of the elements divided by `n`, rounded down to the nearest integer. A subtree of `root` is a tree consisting of `root` and all of its descendants.

30:00

Count Nodes Equal to Average of Subtree
medium
Free written solution
Topics
Companies

Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree.

The average of n elements is the sum of the elements divided by n, rounded down to the nearest integer. A subtree of root is a tree consisting of root and all of its descendants.

Example 1:
Input: {"root":[4,8,5,0,1,null,6]}
Output: 5
Constraints:
  • The number of nodes in the tree is in the range [1,1000][1, 1000].

  • 0≤Node.val≤10000 \leq \text{Node.val} \leq 1000

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[4,8,5,0,1,null,6]}

A node needs the sum and the size of its whole subtree, and both come from its children. So walk post-order: each call returns (sum, size) to its parent.

485016

combine at the current node

Post-order: children first, then the parent.

count

0

matches

none yet

current node + its subtree
left child result
right child result
value = floor(sum / size)
Variables
VariableValue
nodenull
total-
size-
avg-
count0
DepthFunction Call
Stack empty
0/10