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.

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.

思路:divide and conquer,用node class来定义返回的值,这里用到sum,count,average。

DFS返回的物理意义就是:包含当前node的整个子树的sum,count,average ;

错误的地方是:没有加入average,每次进行计算浪费时间还不如算完了,直接传入下一层;多个变量average,省去很多操作;

/**
 * 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 {
    public class Node {
        public double sum;
        public int count;
        public double average;
        public Node(double sum, int count, double average) {
            this.sum = sum;
            this.count = count;
            this.average = average;
        }
    }
    
    public double maximumAverageSubtree(TreeNode root) {
        double[] res = {0.0};
        maximumAverageSubtreeHelper(root, res);
        return res[0];
    }
    

    private Node maximumAverageSubtreeHelper(TreeNode root, double[] res) {
        if(root == null) {
            return new Node(0.0, 0, 0.0);
        }
        
        Node leftnode = maximumAverageSubtreeHelper(root.left, res);
        Node rightnode = maximumAverageSubtreeHelper(root.right, res);
        
        double localmax = Math.max(leftnode.average, rightnode.average);
        double includemax = (leftnode.sum + rightnode.sum + root.val) / (leftnode.count + rightnode.count + 1);
        
        res[0] = Math.max(res[0], Math.max(localmax, includemax));
        
        return new Node(leftnode.sum + rightnode.sum + root.val, 
                        leftnode.count + rightnode.count + 1,
                        includemax);
        
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值