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
The average value of a subtree is calculated as:
Goal: Return the maximum average value found among all subtrees.
Note: Answers within 10-5 of the actual answer will be accepted.
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 nodesGoal: 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
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
โ 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
โ 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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code