Given the root
of a binary tree, find the maximum average value of any subtree of that tree.
(A subtree of a tree is any node of that tree plus all its descendants. The average value of a tree is the sum of its values, divided by the number of nodes.)
Example 1:
Input: [5,6,1] Output: 6.00000 Explanation: 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 is 6 which is the maximum.
Note:
- The number of nodes in the tree is between
1
and5000
. - Each node will have a value between
0
and100000
. - Answers will be accepted as correct if they are within
10^-5
of the correct answer.
思路:divide and conquer,用node class来定义返回的值,这里用到sum,count,average。
DFS返回的物理意义就是:包含当前node的整个子树的sum,count,average ;
错误的地方是:没有加入average,每次进行计算浪费时间还不如算完了,直接传入下一层;多个变量average,省去很多操作;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public class Node {
public double sum;
public int count;
public double average;
public Node(double sum, int count, double average) {
this.sum = sum;
this.count = count;
this.average = average;
}
}
public double maximumAverageSubtree(TreeNode root) {
double[] res = {0.0};
maximumAverageSubtreeHelper(root, res);
return res[0];
}
private Node maximumAverageSubtreeHelper(TreeNode root, double[] res) {
if(root == null) {
return new Node(0.0, 0, 0.0);
}
Node leftnode = maximumAverageSubtreeHelper(root.left, res);
Node rightnode = maximumAverageSubtreeHelper(root.right, res);
double localmax = Math.max(leftnode.average, rightnode.average);
double includemax = (leftnode.sum + rightnode.sum + root.val) / (leftnode.count + rightnode.count + 1);
res[0] = Math.max(res[0], Math.max(localmax, includemax));
return new Node(leftnode.sum + rightnode.sum + root.val,
leftnode.count + rightnode.count + 1,
includemax);
}
}