Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.69 KB | None | 0 0
  1. double max = Integer.MIN_VALUE;
  2. TreeNode maxNode = null;
  3.  
  4. public TreeNode maximumAverageSubtree(TreeNode root) {
  5.     if (root == null) return null;
  6.     helper(root);
  7.     return maxNode;
  8. }
  9.  
  10. private double[] helper(TreeNode root) {
  11.     if (root == null) return new double[] {0, 0};
  12.  
  13.     double curTotal = root.val;
  14.     double count = 1;
  15.     for (TreeNode child : root.children) {
  16.         double[] cur = helper(child);
  17.         curTotal += cur[0];
  18.         count += cur[1];
  19.     }        
  20.     double avg = curTotal / count;
  21.     if (count > 1 && avg > max) { //taking "at least 1 child" into account
  22.         max = avg;
  23.         maxNode = root;
  24.     }
  25.     return new double[] {curTotal, count};
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement