In the Maximum Average Subtree problem, you are given the root of a binary tree. The "average" of a subtree is the sum of all its node values divided by the total number of nodes in that subtree. A subtree includes a specific node and all of its descendants. Your goal is to calculate the average for every possible subtree and return the maximum average value found.
This is a textbook Post-Order Tree Traversal problem. Interviewers ask it because calculating an average requires two distinct pieces of information: a sum and a count. It tests a candidate's ability to create a custom data structure (or array) to pass multiple pieces of state up a recursive call stack, avoiding redundant calculations.
This problem uses Depth-First Search (Post-Order Traversal).
[sum, count] for the current subtree.total_sum for the current node is node.val + left.sum + right.sum.total_count for the current node is 1 + left.count + right.count.(double) total_sum / total_count. Update a global max_average variable if this is the highest seen so far.[total_sum, total_count] to the parent.Tree:
5
/ \
6 1
DFS starts at root 5.
max_avg = 6.0. Returns [6, 1].max_avg remains 6.0. Returns [1, 1].total_sum = .total_count = .max_avg remains 6.0.
The maximum average subtree is the one rooted at 6, with an average of 6.0.A frequent mistake is writing a helper function that calculates the sum, another helper that calculates the count, and calling both on every node. This top-down approach recalculates the same subtrees repeatedly, resulting in an time complexity. By passing the state upwards (bottom-up), each node is visited exactly once, yielding an optimal solution. Also, watch out for integer division! You must cast the sum to a double before dividing.
When an interview question requires you to compute a metric based on multiple properties of a subtree (like sum AND count, or min AND max), immediately define a custom State class (e.g., class State { int sum; int count; }) or return an int[]. Returning these objects from your post-order DFS is the cleanest way to orchestrate complex tree aggregations.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Equal Tree Partition | Medium | Solve | |
| Insufficient Nodes in Root to Leaf Paths | Medium | Solve | |
| Binary Tree Coloring Game | Medium | Solve | |
| Maximum Product of Splitted Binary Tree | Medium | Solve | |
| Delete Leaves With a Given Value | Medium | Solve |