Description:
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 and 5000.
- Each node will have a value between 0 and 100000.
- Answers will be accepted as correct if they are within 10^-5 of the correct answer.
Analysis:
- 首先定义一个类成员变量
max
用来表示这个题目的解。 - 对于这颗树上的任何一个结点,用递归获得这个结点的左子树和右子树的相关数据(sum, count), 然后比较左子树的平均结点值,右子树的平均结点值,以及包含这个结点的整棵树的平均结点值,取三者的最大值去更新变量
max
.
Code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public double max;
public double maximumAverageSubtree(TreeNode root) {
findMaxAvgSubtree(root);
return max;
}
public double[] findMaxAvgSubtree(TreeNode node) {
if(node == null) {
return new double[]{0, 0}; // {sum, count}
}else{
// The data of the left subtree of the node.
double[] leftData = findMaxAvgSubtree(node.left);
// The data of the right subtree of the node.
double[] rightData = findMaxAvgSubtree(node.right);
// avg: the avg value of the nodes in the whole tree
// avg1: the avg value of the nodes in the left subtree
// avg2: the avg value of the nodes in the right subtree
double avg = 0.0, avg1 = 0.0, avg2 = 0.0;
if(leftData[1] != 0) {
avg1 = leftData[0] * 1.0 / leftData[1];
}
if(rightData[1] != 0) {
avg2 = rightData[0] * 1.0 / rightData[1];
}
avg = (leftData[0] + rightData[0] + node.val) * 1.0 / (leftData[1] + rightData[1] + 1);
avg = Math.max(avg, Math.max(avg1, avg2));
// Update max variable.
max = Math.max(max, avg);
// Construct the data of the node.
double[] data = new double[]{leftData[0] + rightData[0] + node.val, leftData[1] + rightData[1] + 1};
return data;
}
}
}