
Input: root =[5,6,1]Output: 6.00000Explanation:
For the node with value =5 we have an average of(5+6+1)/3=4.For the node with value =6 we have an average of 6/1=6.For the node with value =1 we have an average of 1/1=1.So the answer is6 which is the maximum.
Example 2:
1
2
Input: root =[0,null,1]Output: 1.00000
Constraints:
The number of nodes in the tree is in the range [1, 10^4].
To find the maximum average of any subtree, we need to compute the sum and count of nodes for every subtree. A postorder DFS allows us to gather this information for each node, and we can update the maximum average as we traverse.
classSolution {
double ans = 0;
publicdoublemaximumAverageSubtree(TreeNode root) {
dfs(root);
return ans;
}
privateint[]dfs(TreeNode node) {
if (node ==null) returnnewint[]{0, 0};
int[] l = dfs(node.left), r = dfs(node.right);
int s = l[0]+ r[0]+ node.val;
int c = l[1]+ r[1]+ 1;
ans = Math.max(ans, s * 1.0/ c);
returnnewint[]{s, c};
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
var ans = 0.0funmaximumAverageSubtree(root: TreeNode?): Double {
fundfs(node: TreeNode?): Pair<Int, Int> {
if (node ==null) return0 to 0val(ls, lc) = dfs(node.left)
val(rs, rc) = dfs(node.right)
val s = ls + rs + node.`val`
val c = lc + rc + 1 ans = maxOf(ans, s.toDouble()/c)
return s to c
}
dfs(root)
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defmaximumAverageSubtree(self, root: Optional[TreeNode]) -> float:
self.ans =0defdfs(node: Optional[TreeNode]) -> tuple[int, int]:
ifnot node:
return0, 0 ls, lc = dfs(node.left)
rs, rc = dfs(node.right)
s = ls + rs + node.val
c = lc + rc +1 self.ans = max(self.ans, s / c)
return s, c
dfs(root)
return self.ans