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)
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.
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.
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:
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.
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.