我写的
/** * 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 TreeNode node; private double maxAverage = Double.MIN_VALUE; public TreeNode findSubtree2(TreeNode root) { // Write your code here helper(root); return node; } private double helper(TreeNode root) { if (root == null) { return 0; } //改成double double left = helper(root.left); double right = helper(root.right); double sum = root.val + left + right; int n = count(root); if (sum / n > maxAverage) { maxAverage = sum / n; node = root; } return sum; } private int count(TreeNode root) { if (root == null) { return 0; } int leftcount = count(root.left); int rightcount = count(root.right); return leftcount + rightcount + 1; } }