Want Help Cracking FAANG?

(Then click this)

×
Back to Main Page

2265. Count Nodes Equal to Average of Subtree - Leetcode Solution


💡 Step-by-Step Thought Process

  1. Understand the problem: Count nodes in a binary tree where the node’s value equals the average of its subtree’s node values (integer division).
  2. Initialize a list (num_nodes) with a single element 0 to count matching nodes.
  3. Define a DFS function that returns a tuple of the number of nodes and sum of values in a subtree.
  4. If the root is None, return (0, 0).
  5. Recursively compute the number of nodes (N_left) and sum (summ_left) for the left subtree.
  6. Compute the same for the right subtree (N_right, summ_right).
  7. Calculate the total nodes (N) as 1 plus N_left plus N_right and total sum (summ) as root value plus summ_left plus summ_right.
  8. Compute the average as summ divided by N (integer division).
  9. If the root’s value equals the average, increment num_nodes[0].
  10. Return (N, summ).
  11. Call DFS on the root and return num_nodes[0].

Code Solution

class Solution:
    def averageOfSubtree(self, root: TreeNode) -> int:
        num_nodes = [0]

        def dfs(root):
            if not root:
                return (0, 0)
            
            N_left, summ_left = dfs(root.left)
            N_right, summ_right = dfs(root.right)

            N = 1 + N_left + N_right
            summ = root.val + summ_left + summ_right
            avg = summ // N

            if root.val == avg:
                num_nodes[0] += 1

            return (N, summ)
        
        dfs(root)
        return num_nodes[0]
        # Time: O(N)
        # Space: O(N)
        
    

                

                

                

                

Detailed Explanation

Problem Overview

The "Count Nodes Equal to Average of Subtree" problem focuses on binary trees. You are given a binary tree, and your task is to count how many nodes have a value equal to the average of all nodes in their respective subtree (including themselves). The average must be calculated using integer division. This question tests your understanding of depth-first search (DFS), tree traversal, and recursive aggregation of node data.

Key Insights and Approach

The most important observation is that at each node, we need to compute two things for its entire subtree: the total number of nodes and the total sum of those nodes’ values. With this information, we can easily compute the average for the subtree and check whether it equals the value of the root node of that subtree.

A recursive depth-first search (DFS) approach is ideal here. As we traverse the tree from the bottom up, each recursive call can return both the number of nodes and the sum of values in the subtree rooted at the current node. Once we have these values, we check whether the current node’s value equals the computed average using integer division.

Step-by-Step Strategy

To solve this efficiently, we define a recursive helper function that visits each node and returns a tuple: (count_of_nodes_in_subtree, sum_of_subtree_values).

For each node:

  • Recursively compute subtree size and value sum for the left child.
  • Do the same for the right child.
  • Combine the counts and sums from both children with the current node’s value.
  • Calculate the average by dividing the total sum by the total count (using integer division).
  • Check if the current node’s value matches this average. If it does, increment a global counter.

Time and Space Complexity

  • Time Complexity: O(n), where n is the number of nodes in the binary tree. Each node is visited exactly once, and all necessary computations are performed in constant time per node.
  • Space Complexity: O(h), where h is the height of the tree, due to the recursion stack. In the worst case (a skewed tree), this can be O(n).

Why This Approach Works

This method is both elegant and efficient because it leverages the natural structure of the tree and avoids unnecessary recomputation. By gathering data in a post-order fashion (left, right, root), we ensure that each subtree is fully processed before its result is used in a parent’s calculation. This enables a one-pass solution without auxiliary data structures or repeated traversals.

Conclusion

Counting nodes equal to the average of their subtree reinforces recursive thinking and showcases how to aggregate and compare subtree information efficiently. This problem also offers a practical example of combining multiple return values in recursive tree functions, which is a useful technique in more complex tree-based algorithms.

Get Personalized Support at AlgoMap Bootcamp 💡