public class Solution {
/*
* @param root: the root of binary tree
* @return: the root of the maximum average of subtree
*/
private class Tuple {
int sum, count;
Tuple(int sum, int count) {
this.sum = sum;
this.count = count;
}
}
private int currSum;
private int currCount;
private TreeNode currRoot;
public TreeNode findSubtree2(TreeNode root) {
helper(root);
return currRoot;
}
private Tuple helper(TreeNode root) {
if (root == null) return new Tuple(0, 0);
Tuple left = helper(root.left);
Tuple right = helper(root.right);
int sum = left.sum + right.sum + root.val;
int count = left.count + right.count + 1;
if (currRoot == null || currSum * count < currCount * sum) {
currSum = sum;
currCount = count;
currRoot = root;
}
return new Tuple(sum, count);
}
} class Solution:
# @param {TreeNode} root the root of binary tree
# @return {TreeNode} the root of the maximum average of subtree
sum, num, root = 0, 0, None
def findSubtree2(self, root):
def helper(node):
"""
param: TreeNode node
retype: int sum, int num
"""
if not node:
return 0, 0
lsum, lnum = helper(node.left)
rsum, rnum = helper(node.right)
sum = lsum + rsum + node.val
num = lnum + rnum + 1
if (not self.root) or (self.sum * num < sum * self.num):
self.sum = sum
self.num = num
self.root = node
return sum, num
helper(root)
return self.root