LeetCode solutions

2347. Count Nodes Equal to Average of Subtree

My accepted Python solution to LeetCode problem 2347, Count Nodes Equal to Average of Subtree, running in 36ms.

  • Difficulty: Medium
  • Python
  • Runtime 36ms
  • Memory 17.8MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 36ms, memory 17.8MB, accepted 2025-12-30.

python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def averageOfSubtree(self, root: Optional[TreeNode]) -> int:
        self.count = 0
        
        def dfs(node):
            if not node:
                return 0, 0  # (sum, count)
            
            left_sum, left_count = dfs(node.left)
            right_sum, right_count = dfs(node.right)
            
            total_sum = left_sum + right_sum + node.val
            total_count = left_count + right_count + 1
            
            avg = total_sum // total_count
            
            if avg == node.val:
                self.count += 1
            
            return total_sum, total_count
        
        dfs(root)
        return self.count

Source