首页 > 其他 > 详细

1120. Maximum Average Subtree 子树平均值的最大值

时间:2021-08-30 03:01:02      阅读:6      评论:0      收藏:0      [点我收藏+]

Given the root of a binary tree, return the maximum average value of a subtree of that tree. Answers within 10-5 of the actual answer will be accepted.

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: root = [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.

Example 2:

Input: root = [0,null,1]
Output: 1.00000

还是dc的模板,但是

是从这里递归出去的,所以可以用+1来计算子节点的数量
int number = left + right + 1;

https://leetcode.com/problems/maximum-average-subtree/discuss/715694/Java-0ms-simple

class Solution {
    private double average = 0;
    public double maximumAverageSubtree(TreeNode root) {
        helper(root);
        return average;
    }
    
    private int helper(TreeNode root){
        if(root == null)
            return 0;
        int left = helper(root.left);
        int right = helper(root.right);
        int number = left + right + 1;
        if(left != 0)
            root.val += root.left.val;
        if(right != 0)
            root.val += root.right.val;
        average = Math.max(average, (double)(root.val) / number);
        return number;
    }
}

 

 

1120. Maximum Average Subtree 子树平均值的最大值

原文:https://www.cnblogs.com/immiao0319/p/15201690.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!