Maximum average of subtree values in a given Binary Tree | 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 } ; Given tree ; Function call ; Print answer
class TreeNode { constructor ( v ) { this . val = v ; this . children = [ ] ; } } let ans = 0.0 ; function MaxAverage ( root ) { if ( root . children != null && root . children . length == 0 ) { ans = Math . max ( ans , root . val ) ; return [ root . val , 1 ] ; } let childResult = new Array ( 2 ) ; for ( let i = 0 ; i < childResult . length ; i ++ ) { childResult [ i ] = 0 ; } for ( let child = 0 ; child < root . children . length ; child ++ ) { let childTotal = MaxAverage ( root . children [ child ] ) ; childResult [ 0 ] = childResult [ 0 ] + childTotal [ 0 ] ; childResult [ 1 ] = childResult [ 1 ] + childTotal [ 1 ] ; } let sum = childResult [ 0 ] + root . val ; let count = childResult [ 1 ] + 1 ; ans = Math . max ( ans , sum / count ) ; return [ sum , count ] ; } let root = new TreeNode ( 20 ) ; let left = new TreeNode ( 12 ) ; let right = new TreeNode ( 18 ) ; root . children . push ( left ) ; root . children . push ( right ) ; left . children . push ( new TreeNode ( 11 ) ) ; left . children . push ( new TreeNode ( 3 ) ) ; right . children . push ( new TreeNode ( 15 ) ) ; right . children . push ( new TreeNode ( 8 ) ) ; MaxAverage ( root ) ; document . write ( ans . toFixed ( 1 ) ) ;