---
# System prepended metadata

title: 1120. Maximum Average Subtree
tags: [Leetcode, Tree, Recursion, Medium]

---

# 1120. Maximum Average Subtree
###### tags: `Leetcode` `Medium` `Tree` `Recursion`
Link: https://leetcode.com/problems/maximum-average-subtree/description/
## Code
```python=
class Solution:
    def maximumAverageSubtree(self, root: Optional[TreeNode]) -> float:
        res = [0.0]
        def getAverage(root: TreeNode):
            if root is None:
                return 0, 0
            leftSum, leftCnt = getAverage(root.left)
            rightSum, rightCnt = getAverage(root.right)
            totalSum = leftSum+rightSum+root.val
            totalCnt = leftCnt+rightCnt+1
            res[0] = max(res[0], totalSum/totalCnt)

            return leftSum+rightSum+root.val, leftCnt+rightCnt+1
        
        getAverage(root)
        return res[0]
```