File tree
Expand file treeCollapse file tree1 file changed
+17
-18
lines changed Expand file treeCollapse file tree1 file changed
+17
-18
lines changed Original file line number | Diff line number | Diff line change |
---|
|
14 | 14 | * }
|
15 | 15 | */
|
16 | 16 | class Solution {
|
17 |
| -public int averageOfSubtree(TreeNode root) { |
18 |
| -int[] result = {0}; |
19 |
| -helper(root, result); |
20 |
| -return result[0]; |
21 |
| -} |
22 |
| - |
23 |
| -private int[] helper(TreeNode root, int[] result) { |
24 |
| -if (root == null) { |
25 |
| -return new int[]{0, 0}; |
| 17 | +public int averageOfSubtree(TreeNode root) { |
| 18 | +int[] result = {0}; |
| 19 | +recurse(root, result); |
| 20 | +return result[0]; |
26 | 21 | }
|
27 |
| -int[] left = helper(root.left, result); |
28 |
| -int[] right = helper(root.right, result); |
29 |
| -int sum = left[0] + right[0] + root.val; |
30 |
| -int numOfNodes = left[1] + right[1] + 1; |
31 |
| -int average = sum / numOfNodes; |
32 |
| -if (root.val == average) { |
33 |
| -result[0]++; |
| 22 | + |
| 23 | +private int[] recurse(TreeNode root, int[] result) { |
| 24 | +if (root == null) { |
| 25 | +return new int[]{0, 0}; |
| 26 | +} |
| 27 | +int[] left = recurse(root.left, result); |
| 28 | +int[] right = recurse(root.right, result); |
| 29 | +int sum = left[0] + right[0] + root.val; |
| 30 | +int count = left[1] + right[1] + 1; |
| 31 | +if (count != 0 && sum / count == root.val) { |
| 32 | +result[0]++; |
| 33 | +} |
| 34 | +return new int[]{sum, count}; |
34 | 35 | }
|
35 |
| -return new int[]{sum, numOfNodes}; |
36 |
| -} |
37 | 36 | }
|
You can’t perform that action at this time.
0 commit comments