Maximum Average Subtree Problem
Description
LeetCode Problem 1120.
Given the root of a binary tree, return the maximum average value of a subtree of that tree. Answers within 10^-5 of the actual answer will be accepted.
A subtree of a tree is any node of that tree plus all its descendants.
The average value of a tree is the sum of its values, divided by the number of nodes.
Example 1:

Input: root = [5,6,1]
Output: 6.00000
Explanation:
For the node with value = 5 we have an average of (5 + 6 + 1) / 3 = 4.
For the node with value = 6 we have an average of 6 / 1 = 6.
For the node with value = 1 we have an average of 1 / 1 = 1.
So the answer is 6 which is the maximum.
Example 2:
Input: root = [0,null,1]
Output: 1.00000
Constraints:
- The number of nodes in the tree is in the range
[1, 10^4]. 0 <= Node.val <= 10^5
Solution
Approach: Post-order DFS Returning Sum and Size
The average of a subtree needs its sum and its number of nodes. Both can be built from the children: a node's subtree has sum node.val + leftSum + rightSum and size 1 + leftCount + rightCount. Computing each subtree from scratch would visit nodes many times; a post-order DFS gets every subtree's totals in one pass.
Write dfs(node) that returns (sum, count) for node's subtree ((0, 0) for an empty child). After combining the children, it computes sum / count, updates the best average seen so far, and passes (sum, count) up to the parent.
Do the division in floating point: with integer division, an average like 7 / 2 would become 3. The sums stay small enough for 32-bit integers (at most 10^4 * 10^5 = 10^9).
Complexity: O(n) time, and O(h) extra space for the recursion, where h is the height of the tree.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maximumAverageSubtree(self, root: Optional[TreeNode]) -> float:
best = 0.0
def dfs(node: Optional[TreeNode]) -> Tuple[int, int]:
"""Sum and number of nodes of node's subtree; updates best on the way."""
nonlocal best
if node is None:
return 0, 0
left_sum, left_count = dfs(node.left)
right_sum, right_count = dfs(node.right)
total = node.val + left_sum + right_sum
count = 1 + left_count + right_count
best = max(best, total / count)
return total, count
dfs(root)
return best