|
4 | 4 | * int val;
|
5 | 5 | * TreeNode left;
|
6 | 6 | * TreeNode right;
|
7 |
| - * TreeNode(int x) { val = x; } |
| 7 | + * TreeNode() {} |
| 8 | + * TreeNode(int val) { this.val = val; } |
| 9 | + * TreeNode(int val, TreeNode left, TreeNode right) { |
| 10 | + * this.val = val; |
| 11 | + * this.left = left; |
| 12 | + * this.right = right; |
| 13 | + * } |
8 | 14 | * }
|
9 | 15 | */
|
10 | 16 | class Solution {
|
11 |
| - double maxAvg; |
12 |
| - public double maximumAverageSubtree(TreeNode root) { |
13 |
| - maxAvg = 0.0; |
14 |
| - helper(root); |
15 |
| - return maxAvg; |
16 |
| - } |
17 |
| - |
18 |
| - private int[] helper(TreeNode root) { |
19 |
| - int[] data = new int[2]; |
20 |
| - if (root == null) { |
21 |
| - return data; |
| 17 | + public double maximumAverageSubtree(TreeNode root) { |
| 18 | + double[] result = {0.0}; |
| 19 | + traverse(root, result); |
| 20 | + return result[0]; |
| 21 | + } |
| 22 | + |
| 23 | + private double[] traverse(TreeNode root, double[] result) { |
| 24 | + if (root == null) { |
| 25 | + return new double[]{0.0, 0.0}; |
| 26 | + } |
| 27 | + double[] leftValues = traverse(root.left, result); |
| 28 | + double[] rightValues = traverse(root.right, result); |
| 29 | + double sum = root.val + leftValues[0] + rightValues[0]; |
| 30 | + double count = 1 + leftValues[1] + rightValues[1]; |
| 31 | + double avg = sum / count; |
| 32 | + result[0] = Math.max(result[0], avg); |
| 33 | + return new double[]{sum, count}; |
22 | 34 | }
|
23 |
| - int[] dataLeft = helper(root.left); |
24 |
| - int[] dataRight = helper(root.right); |
25 |
| - data[0] += root.val + dataLeft[0] + dataRight[0]; |
26 |
| - data[1] += 1 + dataLeft[1] + dataRight[1]; |
27 |
| - double avg = ((double) data[0]) / data[1]; |
28 |
| - maxAvg = Math.max(maxAvg, avg); |
29 |
| - return data; |
30 |
| - } |
31 | 35 | }
|
0 commit comments