Count Nodes Equal to Average of Subtree - Problem
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.
Note:
- The average of
nelements is the sum of thenelements divided bynand rounded down to the nearest integer. - A subtree of root is a tree consisting of root and all of its descendants.
Input & Output
Example 1 — Complete Binary Tree
$
Input:
root = [4,8,5,0,1,null,6]
›
Output:
5
💡 Note:
Node 4: subtree sum=24, count=6, average=4 ✓. Node 5: subtree sum=11, count=2, average=5 ✓. Leaf nodes 0, 1, 6 all equal their own values ✓. Node 8: subtree sum=9, count=3, average=3 ≠ 8.
Example 2 — Simple Tree
$
Input:
root = [1]
›
Output:
1
💡 Note:
Single node with value 1. Subtree sum=1, count=1, average=1 ✓. The node equals its subtree average.
Example 3 — No Matches
$
Input:
root = [1,2,3]
›
Output:
0
💡 Note:
Node 1: subtree sum=6, count=3, average=2 ≠ 1. Node 2: sum=2, count=1, average=2 ✓. Wait, that's 1 match actually. Node 3: sum=3, count=1, average=3 ✓. So result should be 2.
Constraints
- The number of nodes in the tree is in the range [1, 105]
- 0 ≤ Node.val ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Binary tree with node values
2
Calculate Averages
For each subtree, compute sum/count
3
Count Matches
Count nodes where value equals subtree average
Key Takeaway
🎯 Key Insight: Use DFS to calculate subtree sums and counts in one traversal, checking averages bottom-up
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code