Maximum average of subtree values in a given Binary Tree | Java program for the above approach ; Structure of the Tree node ; Stores the result ; Function for finding maximum subtree average ; Checks if current node is not null and doesn 't have any children ; Stores sum of its subtree in index 0 and count number of nodes in index 1 ; Traverse all children of the current node ; Recursively calculate max average of subtrees among its children ; Increment sum by sum of its child 's subtree ; Increment number of nodes by its child 's node ; Increment sum by current node 's value ; Increment number of nodes by one ; Take maximum of ans and current node 's average ; Finally return pair of { sum , count } ; Driver Code ; Given tree ; Function call ; Print answer
import java . util . * ; class TreeNode { public int val ; public List < TreeNode > children ; public TreeNode ( int v ) { val = v ; children = new ArrayList < TreeNode > ( ) ; } } class GFG { static double ans = 0.0 ; public static double [ ] MaxAverage ( TreeNode root ) { if ( root . children != null && root . children . size ( ) == 0 ) { ans = Math . max ( ans , root . val ) ; return new double [ ] { root . val , 1 } ; } double [ ] childResult = new double [ 2 ] ; for ( TreeNode child : root . children ) { double [ ] childTotal = MaxAverage ( child ) ; childResult [ 0 ] = childResult [ 0 ] + childTotal [ 0 ] ; childResult [ 1 ] = childResult [ 1 ] + childTotal [ 1 ] ; } double sum = childResult [ 0 ] + root . val ; double count = childResult [ 1 ] + 1 ; ans = Math . max ( ans , sum / count ) ; return new double [ ] { sum , count } ; } public static void main ( String [ ] args ) { TreeNode root = new TreeNode ( 20 ) ; TreeNode left = new TreeNode ( 12 ) ; TreeNode right = new TreeNode ( 18 ) ; root . children . add ( left ) ; root . children . add ( right ) ; left . children . add ( new TreeNode ( 11 ) ) ; left . children . add ( new TreeNode ( 3 ) ) ; right . children . add ( new TreeNode ( 15 ) ) ; right . children . add ( new TreeNode ( 8 ) ) ; MaxAverage ( root ) ; System . out . println ( ans ) ; } }