Problem Description
Given the root of a binary tree, determine the number of nodes such that the value of the node is equal to the average of the values in its subtree. The average is computed by summing all the values in the subtree (including the node itself), dividing by the number of nodes in the subtree, and rounding down to the nearest integer.
Key Insights
- Use depth-first search (DFS) to traverse the tree in a post-order fashion.
- For each node, compute the cumulative sum and count of nodes in its subtree.
- Calculate the average as the floor division of the sum by the count.
- Check if the node's value matches the computed average and increment a global counter accordingly.
Space and Time Complexity
Time Complexity: O(n), where n is the number of nodes in the tree since every node is visited once.
Space Complexity: O(h), where h is the height of the tree, due to recursion stack space (worst-case O(n) for a skewed tree).
Solution
Perform a post-order DFS traversal. For every node:
- Recursively obtain the sum and count of nodes from the left and right subtrees.
- Calculate the current subtree’s sum and total node count.
- Compute the average (using integer division which rounds down).
- Compare the node’s value with the calculated average and update the counter if they match.
- Return the pair (subtree sum, subtree count) to be used for computing the averages in upper recursive calls.