private class HelperType{
public int sum;
public int size;
public HelperType(int sum,int size){
this.size=size;
this.sum=sum;
}
}
public TreeNode currentNode=null;
public HelperType currentData=null;
public HelperType helper(TreeNode root){
if(root==null){
return new HelperType(0,0);
}
HelperType left=helper(root.left);
HelperType right=helper(root.right);
HelperType result=new HelperType(root.val+left.sum+right.sum,1+left.size+right.size);
if(currentNode==null){
currentNode=root;
currentData=result;
}
if(currentData.size*result.sum>currentData.sum*result.size){
currentData=result;
currentNode=root;
}
return result;
}
public TreeNode findSubtree2(TreeNode root){
helper(root);
return currentNode;
}
public class Solution {
/**
* @param root: the root of binary tree
* @return: the root of the maximum average of subtree
*/
private TreeNode maxNode = null;
private Node currentNode = null;
public TreeNode findSubtree2(TreeNode root) {
// write your code here
postOrderTraverse(root);
return maxNode;
}
public Node postOrderTraverse(TreeNode root)
{
if(root == null) return new Node(0,0);
Node left = postOrderTraverse(root.left);
Node right = postOrderTraverse(root.right);
Node result = new Node(left.sum + right.sum + root.val, left.count+right.count+1);
if(maxNode == null)
{
maxNode = root;
currentNode = result;
}
// compare currentNode and result
if(currentNode.sum*result.count < result.sum*currentNode.count)
{
maxNode = root;
currentNode = result;
}
return result;
}
}
class Node
{
int sum;
int count;
Node(int sum, int count)
{
this.sum = sum;
this.count = count;
}
}