Maximum Average Subtree - Problem
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.
Input & Output
Example 1 — Basic Tree
$
Input:
root = [5,6,1]
›
Output:
6.0
💡 Note:
Tree has subtrees: node 5 (avg=4.0), node 6 (avg=6.0), node 1 (avg=1.0). Maximum is 6.0 from the single node 6.
Example 2 — Single Node
$
Input:
root = [1]
›
Output:
1.0
💡 Note:
Only one subtree exists: the root node itself with value 1, so average is 1.0.
Example 3 — Larger Tree
$
Input:
root = [1,null,2,null,3]
›
Output:
3.0
💡 Note:
Right-skewed tree. Node 3 has average 3.0, node 2 has average 2.5, root has average 2.0. Maximum is 3.0.
Constraints
- The number of nodes in the tree is in the range [1, 104]
- -104 ≤ Node.val ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Binary tree with node values
2
Calculate Averages
Find average for each possible subtree
3
Return Maximum
Return the highest average found
Key Takeaway
🎯 Key Insight: Use post-order DFS to calculate subtree statistics efficiently in one pass
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code