LintCode 597: Subtree with Maximum Average 具有最大平均数的子树

问题描述

LintCode 597: Subtree with Maximum Average 具有最大平均数的子树_第1张图片

java实现

/**
 * 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 {
    /**
     * @param root: the root of binary tree
     * @return: the root of the maximum average of subtree
     */
     private class ResultType{
       int sum,size;
       public ResultType (int sum, int size){
           this.sum=sum;
           this.size=size;
       }
    }

    private TreeNode maxAveSubtree=null;//结点
    private ResultType subtreeResult=null;//结点信息

    public TreeNode findSubtree2(TreeNode root) {
        helper(root);
        return maxAveSubtree;
    }
    private ResultType helper(TreeNode root){
        if(root==null)
            return new ResultType(0,0);
        ResultType left=helper(root.left);
        ResultType right=helper(root.right);

        ResultType rootResult=new ResultType(left.sum+right.sum+root.val,left.size+right.size+1);
        //subtreeResult.sum/subtreeResult.size<rootResult.size/rootResult.size会损失精度
        if(maxAveSubtree==null || subtreeResult.sum*rootResult.size<subtreeResult.size*rootResult.sum) {
            maxAveSubtree=root;
            subtreeResult=rootResult;
        }
        return rootResult;
    }
}

你可能感兴趣的:(分治)