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 INPUT Binary Tree Structure 5 6 1 root = [5, 6, 1] Level-order representation Total nodes: 3 Height: 2 ALGORITHM STEPS 1 DFS Post-order Visit children first, then process parent 2 Return (sum, count) Each node returns sum and node count of subtree 3 Calculate Average avg = sum / count at each node 4 Track Maximum Update global max if current avg is higher Subtree Averages: Node 6: 6/1 = 6.0 Node 1: 1/1 = 1.0 Node 5: (5+6+1)/3 = 4.0 FINAL RESULT Maximum Average Subtree 6 Single node subtree has highest average OUTPUT 6.0 OK - Max Found! 6.0 > 4.0 > 1.0 Key Insight: Single-pass DFS returns (sum, count) tuple for each subtree. Calculate average at each node using: avg = sum/count. Track global maximum. Time: O(n), Space: O(h) where h = tree height. Leaf nodes often have highest average since they avoid dilution from smaller children. TutorialsPoint - Maximum Average Subtree | Optimized DFS - Single 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