Given a binary tree, find the subtree with maximum average. Return the root of the subtree.
Notice
LintCode will print the subtree which root is your return node.
It's guaranteed that there is only one subtree with maximum average.
Example
Given a binary tree:
1
/ \
-5 11
/ \ / \
1 2 4 -2
return the node 11.
这道题是easy,在我看来不那么easy。。。
又写了个类才解决,而且代码感觉写的很差。。。
lass Result { public int sum; public int num; public double average; TreeNode node; public Result(int sum, int num, double average, TreeNode node) { this.sum = sum; this.num = num; this.average = average; this.node = node; } } public class Solution { /** * @param root the root of binary tree * @return the root of the maximum average of subtree */ public TreeNode findSubtree2(TreeNode root) { Result rs = helper(root); return rs.node; } public Result helper(TreeNode root) { if (root == null) { return new Result(0, 0, Integer.MIN_VALUE, null); } Result left = helper(root.left); Result right = helper(root.right); Result rs = new Result(0, 0, Integer.MIN_VALUE, root); int sum = left.sum + right.sum + root.val; int num = left.num + right.num + 1; double average = (double) sum / (double) num; if (right.average > left.average) { rs.sum = sum; rs.num = num; rs.average = right.average; rs.node = right.node; } else { rs.sum = sum; rs.num = num; rs.average = left.average; rs.node = left.node; } if (average > rs.average) { rs.sum = sum; rs.num = num; rs.average = average; rs.node = root; } return rs; } }
还可以改良一下用两个全局变量。。。代码可能好点吧
class Result { public int sum; public int num; public Result(int sum, int num) { this.sum = sum; this.num = num; // this.average = average; // this.node = node; } } public class Solution { /** * @param root the root of binary tree * @return the root of the maximum average of subtree */ private TreeNode subTree = null; private double average = Integer.MIN_VALUE; public TreeNode findSubtree2(TreeNode root) { Result rs = helper(root); return subTree; } public Result helper(TreeNode root) { if (root == null) { return new Result(0, 0); } Result left = helper(root.left); Result right = helper(root.right); int sum = left.sum + right.sum + root.val; int num = left.num + right.num + 1; Result rs = new Result(sum, num); double aver = (double) sum / (double) num; if (aver > average) { average = aver; subTree = root; } return rs; } }
反正这个题也是醉了,还是回顾一下吧。