【两次过】Lintcode 597. 具有最大平均数的子树

给一棵二叉树,找到有最大平均值的子树。返回子树的根结点。

样例

给一个二叉树:

     1
   /   \
 -5     11
 / \   /  \
1   2 4    -2 

返回节点 11

注意事项

LintCode会打印出根结点为你返回节点的子树,保证有最大平均数子树只有一棵


解题思路:

Lintcode 596. 最小子树思路一致,只不过求平均值所需要传递的值不仅仅是和,还需要该节点和对应的节点个数,所以为了方便参数传递,设置ResultType类用于存储节点,和与个数。

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

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

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值