In this tree problem, you need to count how many nodes in a binary tree have a value equal to the average of all the values in their subtree. The average is calculated as the sum of all node values in the subtree divided by the number of nodes in the subtree, rounded down to the nearest integer.
This is a standard "Medium" tree question asked by Microsoft and Google to test Depth-First Search (DFS) skills. It requires you to aggregate information from the bottom up. It evaluations your ability to return multiple values (sum and count) from a recursive function and perform calculations based on those values at each node.
This problem uses the Post-order Traversal (DFS) pattern. Since a node's average depends on its children's subtrees, you must process the children first. Each recursive call returns a pair: {sum_of_values, count_of_nodes} for the subtree rooted at that node. At the current node, you calculate the total sum and count, compute the average, and increment a global counter if it matches the node's value.
Subtree:
4
/
8 5
/ \
0 1 6
A common mistake is performing a separate traversal for each node to calculate its subtree average, which leads to complexity. Another mistake is using floating-point division when integer division (truncation) is requested. Failing to handle the base case (null nodes) correctly can also lead to errors.
Practice returning custom objects or arrays from recursive functions. Tree problems that require "bottom-up" aggregation are extremely common, and being able to pass multiple pieces of information up the tree is a vital skill.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Sum Root to Leaf Numbers | Medium | Solve | |
| Binary Tree Pruning | Medium | Solve | |
| Flip Equivalent Binary Trees | Medium | Solve | |
| Binary Tree Longest Consecutive Sequence | Medium | Solve | |
| Distribute Coins in Binary Tree | Medium | Solve |