Maximum Average Subtree - Problem
Find the Maximum Average Subtree

Imagine you're analyzing different departments in a company, where each department is represented as a node in a hierarchical tree structure. Each department has a performance score, and you want to find which department (including all its sub-departments) has the highest average performance.

Given the root of a binary tree where each node contains a numerical value, your task is to find the maximum average value among all possible subtrees. A subtree consists of any node plus all of its descendants (children, grandchildren, etc.).

The average value of a subtree is calculated as: sum of all node values / number of nodes

Goal: Return the maximum average value found among all subtrees.
Note: Answers within 10-5 of the actual answer will be accepted.

Input & Output

example_1.py โ€” Basic Tree
$ Input: root = [5,6,1]
โ€บ Output: 6.0
๐Ÿ’ก Note: The tree has subtrees: [5,6,1] with average 4.0, [6] with average 6.0, and [1] with average 1.0. The maximum is 6.0 from the single node subtree containing only 6.
example_2.py โ€” Larger Tree
$ Input: root = [0,null,1]
โ€บ Output: 1.0
๐Ÿ’ก Note: The tree has subtrees: [0,1] with average 0.5 and [1] with average 1.0. The maximum is 1.0.
example_3.py โ€” Single Node
$ Input: root = [1]
โ€บ Output: 1.0
๐Ÿ’ก Note: A tree with only one node has only one subtree [1] with average 1.0.

Visualization

Tap to expand
CEODeptSalesDeptITDeptPerformance: 6Employees: 1Average: 6.0 ๐Ÿ†Performance: 1Employees: 1Average: 1.0Total Performance: 12Total Employees: 3 โ†’ Avg: 4.0๐ŸŽฏ Winner: Sales Department with 6.0 average!
Understanding the Visualization
1
Start from Leaf Departments
Calculate individual performance scores (6.0 and 1.0)
2
Move Up Hierarchy
Parent departments receive performance data from children
3
Calculate Combined Performance
Root department: (5+6+1)/3 = 4.0 average
4
Find Maximum
Compare all averages: max(6.0, 1.0, 4.0) = 6.0
Key Takeaway
๐ŸŽฏ Key Insight: By using post-order traversal, we calculate each subtree's statistics exactly once, achieving optimal O(n) time complexity while tracking the maximum average across all departments.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Each node is visited exactly once in the DFS traversal

n
2n
โœ“ Linear Growth
Space Complexity
O(h)

Recursion stack depth equals tree height h, which is O(log n) for balanced trees, O(n) for skewed trees

n
2n
โœ“ Linear Space

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • -104 โ‰ค Node.val โ‰ค 104
  • All nodes in the tree are guaranteed to be unique
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
42.0K Views
Medium Frequency
~15 min Avg. Time
1.4K 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