1120. Maximum Average Subtree
Input:
20
/ \
12 18
/ | \ / \
11 2 3 15 8
Output: 18
Explanation:
There are 3 nodes which have children in this tree:
12 => (11 + 2 + 3 + 12) / 4 = 7
18 => (18 + 15 + 8) / 3 = 13.67
20 => (12 + 11 + 2 + 3 + 18 + 15 + 8 + 20) / 8 = 11.125
18 has the maximum average so output 18.public class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val,List<Node> _children) {
val = _val;
children = _children;
}
};
double max = 0;
Node res = null;
public int[] computeAvg(Node root){
if(root == null) return new int[]{0, 0};
int val = root.val, count = 1;
for(Node child: root.children){
int[] arr = computeAvg(child);
val += arr[0]; count += arr[1];
}
if(count > 1 && (res == null || val / (0.0 + count) > max)){
res = root;
max = val / (0.0 + count);
}
return new int[]{val, count};
}
public Node subtreeWithMaximumAverage(Node root){
if(root == null) return res;
computeAvg(root);
return res;
}Last updated