LeetCode 1120. Maximum Average Subtree(Medium)

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:

  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.

Analysis:

  1. 首先定义一个类成员变量max用来表示这个题目的解。
  2. 对于这颗树上的任何一个结点,用递归获得这个结点的左子树和右子树的相关数据(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;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值