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
Maximum Average Subtree Problem OverviewInput Tree561Subtree Averages• Subtree rooted at 5: sum = 5 + 6 + 1 = 12 count = 3 nodes average = 12/3 = 4.0• Subtree rooted at 6: sum = 6 count = 1 node average = 6/1 = 6.0 ★• Subtree rooted at 1: sum = 1 count = 1 node average = 1/1 = 1.0Result6.0MaximumThe subtree with node 6has the highest average
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
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
32.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen