码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] 597. Subtree with Maximum Average

时间:2020-03-05 13:42:34      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:int   script   down   lin   lob   return   put   body   out   

Given a binary tree, find the subtree with maximum average. Return the root of the subtree.

 

Example 1

Input:
{1,-5,11,1,2,4,-2}
Output:11
Explanation:
The tree is look like this:
     1
   /    -5     11
 / \   /  1   2 4    -2 
The average of subtree of 11 is 4.3333, is the maximun.

Example 2

Input:
{1,-5,11}
Output:11
Explanation:
     1
   /    -5     11
The average of subtree of 1,-5,11 is 2.333,-5,11. So the subtree of 11 is the maximun.

public class Solution {
    private class ResType {
        int sum;
        int size;
        public ResType(int sum, int size) {
            this.sum = sum;
            this.size = size;
        }
    }
    /**
     * @param root: the root of binary tree
     * @return: the root of the maximum average of subtree
     */
    TreeNode maxNode = null;
    ResType globalNode = null;
    public TreeNode findSubtree2(TreeNode root) {
        // write your code here
        helper(root);
        return maxNode;
    }
    
    private ResType helper(TreeNode root) {
        if (root == null) {
            return new ResType(0, 0);
        }
        ResType left = helper(root.left);
        ResType right = helper(root.right);
        int curSum = left.sum + right.sum + root.val;
        int curSize = left.size + right.size + 1;
        ResType cur = new ResType(curSum, curSize);
        if (maxNode == null || curSum * globalNode.size > curSize * globalNode.sum) {
            globalNode = cur;
            maxNode = root;
        }
        return cur;
    }
}

 

[LintCode] 597. Subtree with Maximum Average

标签:int   script   down   lin   lob   return   put   body   out   

原文地址:https://www.cnblogs.com/xuanlu/p/12419352.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!