Count Nodes Equal to Average of Subtree - Problem
Given the root of a binary tree, you need to count how many nodes have a special property: the node's value equals the average of all values in its subtree.
๐ณ What is a subtree? For any node, its subtree includes the node itself and all of its descendants (children, grandchildren, etc.).
๐ How is the average calculated? Take the sum of all values in the subtree, divide by the count of nodes, and round down to the nearest integer (floor division).
Example: If a subtree has values [4, 8, 5], the average is (4+8+5)/3 = 17/3 = 5.67... โ rounds down to 5
Your task is to return the total count of nodes that satisfy this condition.
Input & Output
example_1.py โ Basic Tree
$
Input:
root = [4,8,5,0,1,null,6]
โบ
Output:
5
๐ก Note:
Node 4: subtree [4,8,5,0,1,6] โ sum=24, count=6, avg=4 โ
Node 8: subtree [8,0,1] โ sum=9, count=3, avg=3 โ
Node 5: subtree [5,6] โ sum=11, count=2, avg=5 โ
Node 0: subtree [0] โ sum=0, count=1, avg=0 โ
Node 1: subtree [1] โ sum=1, count=1, avg=1 โ
Node 6: subtree [6] โ sum=6, count=1, avg=6 โ
example_2.py โ Single Node
$
Input:
root = [1]
โบ
Output:
1
๐ก Note:
Single node has subtree containing only itself. sum=1, count=1, average=1, so 1==1 is true.
example_3.py โ All Different
$
Input:
root = [1,2,3]
โบ
Output:
2
๐ก Note:
Node 1: subtree [1,2,3] โ sum=6, count=3, avg=2 โ
Node 2: subtree [2] โ sum=2, count=1, avg=2 โ
Node 3: subtree [3] โ sum=3, count=1, avg=3 โ
Constraints
-
The number of nodes in the tree is in the range
[1, 1000] -
0 โค Node.val โค 1000 - The tree is guaranteed to be a valid binary tree
- Average is calculated using integer division (floor division)
Visualization
Tap to expand
Understanding the Visualization
1
Leaf Employees Report
Each leaf employee reports: 'My team size is 1, total salary is my salary, and I'm valid if my salary equals the average (which is just my salary).'
2
Middle Managers Aggregate
Each manager combines reports from subordinates: 'My team size = 1 + subordinates' team sizes, total salary = my salary + subordinates' totals.'
3
Check Manager Validity
Each manager calculates: 'Average = total salary รท team size. Am I valid? My salary == average?'
4
CEO Gets Final Count
The CEO (root) receives the total count of all valid managers in the entire organization.
Key Takeaway
๐ฏ Key Insight: Post-order traversal allows each node to collect complete information from its subtree before making its own decision, enabling a single-pass solution.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code