Maximum Average Subtree — LeetCode 1120 Python Solution

MediumLeetCode PremiumTreeDepth-First SearchBinary Tree
Problem
#1120
Reading time
4 min

The 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.

Example

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.

Python solution

Python
# 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:
        def dfs(root):
            if root is None:
                return 0, 0
            ls, ln = dfs(root.left)
            rs, rn = dfs(root.right)
            s = root.val + ls + rs
            n = 1 + ln + rn
            nonlocal ans
            ans = max(ans, s / n)
            return s, n

        ans = 0
        dfs(root)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1120. Maximum Average Subtree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1120. Maximum Average Subtree?
LeetCode 1120. Maximum Average Subtree is rated Medium on LeetCode.
What is the time complexity of LeetCode 1120. Maximum Average Subtree?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1120. Maximum Average Subtree?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1120. Maximum Average Subtree cover?
LeetCode 1120. Maximum Average Subtree is tagged Tree, Depth-First Search and Binary Tree on LeetCode.
Is LeetCode 1120. Maximum Average Subtree a premium problem?
Yes. LeetCode 1120. Maximum Average Subtree is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview