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 n elements is the sum of the n elements divided by n and 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
Count Nodes Equal to Average of Subtree485016Sum: 24, Count: 6, Avg: 4 ✓Sum: 9, Count: 3, Avg: 3 ✗Sum: 11, Count: 2, Avg: 5 ✓Subtree Analysis✓ Node 4: (4+8+5+0+1+6)/6 = 4✓ Node 5: (5+6)/2 = 5✗ Node 8: (8+0+1)/3 = 3 ≠ 8✓ Node 0: 0/1 = 0✓ Node 1: 1/1 = 1✓ Node 6: 6/1 = 6Total: 5 nodes matchGreen circles = matches averageRed circle = doesn't match
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
Asked in
Facebook 15 Amazon 12 Microsoft 8
23.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen