给一棵二叉树,找到有最大平均值的子树。返回子树的根结点。
样例
给一个二叉树:
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;
}
}