1120. Maximum Average Subtree

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.

 1 class Solution {
 2     double res = Integer.MIN_VALUE;
 3 
 4     public double maximumAverageSubtree(TreeNode root) {
 5         dfs(root);
 6         return res;
 7     }
 8 
 9     private int[] dfs(TreeNode root) {
10         if (root == null) {
11             return new int[] {0, 0};
12         }
13         int[] l = dfs(root.left), r = dfs(root.right);
14         int sum = l[0] + r[0] + root.val, count = l[1] + r[1] + 1;
15         res = Math.max(1.0 * sum / count, res);
16         return new int[] {sum, count};
17     }
18 }

 

posted @ 2021-03-13 13:42  北叶青藤  阅读(138)  评论(0编辑  收藏  举报