|
| 1 | +/** |
| 2 | +
|
| 3 | +Given the root of a binary tree, find the maximum average value of any subtree of that tree. |
| 4 | +(A subtree of a tree is any node of that tree plus all its descendants. |
| 5 | +The average value of a tree is the sum of its values, divided by the number of nodes.) |
| 6 | +
|
| 7 | +Example 1: |
| 8 | +
|
| 9 | +Input: [5,6,1] |
| 10 | +Output: 6.00000 |
| 11 | +Explanation: |
| 12 | +For the node with value = 5 we have an average of (5 + 6 + 1) / 3 = 4. |
| 13 | +For the node with value = 6 we have an average of 6 / 1 = 6. |
| 14 | +For the node with value = 1 we have an average of 1 / 1 = 1. |
| 15 | +So the answer is 6 which is the maximum. |
| 16 | +
|
| 17 | +Note: |
| 18 | +
|
| 19 | +The number of nodes in the tree is between 1 and 5000. |
| 20 | +Each node will have a value between 0 and 100000. |
| 21 | +Answers will be accepted as correct if they are within 10^-5 of the correct answer. |
| 22 | +
|
| 23 | +*/ |
| 24 | + |
| 25 | +/** |
| 26 | + * Definition for a binary tree node. |
| 27 | + * function TreeNode(val) { |
| 28 | + * this.val = val; |
| 29 | + * this.left = this.right = null; |
| 30 | + * } |
| 31 | + */ |
| 32 | +/** |
| 33 | + * @param {TreeNode} root |
| 34 | + * @return {number} |
| 35 | + */ |
| 36 | +const maximumAverageSubtree = function(root) { |
| 37 | + let max = -Number.MIN_VALUE; |
| 38 | + function helper(root) { |
| 39 | + if (!root) return [0, 0]; // [value, number of nodes] |
| 40 | + const [lTotal, lNum] = helper(root.left); |
| 41 | + const [rTotal, rNum] = helper(root.right); |
| 42 | + max = Math.max(max, (rTotal + lTotal + root.val) / (rNum + lNum + 1)); |
| 43 | + return [lTotal + rTotal + root.val, lNum + rNum + 1]; |
| 44 | + } |
| 45 | + helper(root); |
| 46 | + return max; |
| 47 | +}; |
0 commit comments