#2265

Count Nodes Equal to Average of Subtree

Medium
TreeDepth-First SearchBinary TreeDepth-First SearchTree Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(h)
💡

Intuition

Time O(n)Space O(h)

The optimal approach uses a single depth-first search (DFS) to calculate both the sum and count of nodes in each subtree in one traversal, making it much more efficient.

⚙️

Algorithm

3 steps
  1. 1Step 1: Perform a DFS on the tree, calculating the sum and count of nodes for each subtree.
  2. 2Step 2: For each node, check if its value equals the average of its subtree using the sum and count obtained.
  3. 3Step 3: Count the nodes that satisfy the condition.
solution.py23 lines
1# Full working Python code
2class TreeNode:
3    def __init__(self, val=0, left=None, right=None):
4        self.val = val
5        self.left = left
6        self.right = right
7
8class Solution:
9    def averageOfSubtree(self, root: TreeNode) -> int:
10        def dfs(node):
11            if not node:
12                return (0, 0)
13            left_sum, left_count = dfs(node.left)
14            right_sum, right_count = dfs(node.right)
15            total_sum = left_sum + right_sum + node.val
16            total_count = left_count + right_count + 1
17            if node.val == total_sum // total_count:
18                self.count += 1
19            return (total_sum, total_count)
20
21        self.count = 0
22        dfs(root)
23        return self.count

Complexity note: The time complexity is linear because we visit each node exactly once. The space complexity is O(h) due to the recursion stack, where h is the height of the tree.

  • 1Understanding how to calculate the average requires both the sum and the count of nodes in a subtree.
  • 2Using a single DFS traversal can significantly improve efficiency compared to recalculating sums for each node.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.