Friday, November 13, 2020

LeetCode [1120] Maximum Average Subtree

1120. Maximum Average Subtree
Medium

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:

  1. The number of nodes in the tree is between 1 and 5000.
  2. Each node will have a value between 0 and 100000.
  3. Answers will be accepted as correct if they are within 10^-5 of the correct answer.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
 * 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 {
    double maxAverage = Integer.MIN_VALUE;
    public double maximumAverageSubtree(TreeNode root) {
        helper(root);
        return maxAverage;
    }
    
    
    //sum, count
    double[] helper(TreeNode node){
        if(node==null) return new double[0];
        double sum = node.val, count = 1;
        if(node.left!=null){
            double[] left = helper(node.left);
            sum += left[0];
            count += left[1];
        }
        
        if(node.right!=null){
            double[] right = helper(node.right);
            sum += right[0];
            count += right[1];
        }

        maxAverage = Math.max(maxAverage, sum/count);
        return new double[]{sum, count};
    }
}

No comments:

Post a Comment