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: 2
💡 Note: Node 1: subtree sum=6, count=3, average=2 ≠ 1. Node 2: sum=2, count=1, average=2 ✓. Node 3: sum=3, count=1, average=3 ✓. Total matching nodes: 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 Subtree INPUT 4 8 5 0 1 6 root = [4,8,5,0,1,null,6] 7 nodes in binary tree ALGORITHM STEPS 1 DFS Post-Order Process children first, then parent node 2 Return (sum, count) Each node returns subtree sum and node count 3 Calculate Average avg = total_sum / count (integer division) 4 Check & Count If node.val == avg, increment result counter Example: Node 8 Subtree: 8, 0, 1 Sum = 9, Count = 3 Avg = 9/3 = 3 8 != 3, not counted FINAL RESULT 4 OK 8 5 OK 0 OK 1 OK 6 OK Match (5) No Match (1) Output: 5 5 nodes have value equal to their subtree average Key Insight: Use post-order DFS to compute subtree sum and count in a single traversal. Each node returns (sum, count) tuple to parent. Time: O(n), Space: O(h) where h = tree height. Leaves always match since their average equals their own value. Avoid recalculating by passing info up the recursion. TutorialsPoint - Count Nodes Equal to Average of Subtree | Optimized DFS - Single Traversal
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