|
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 | 17 | public int closestValue(TreeNode root, double target) {
|
12 |
| - int[] ans = {0}; |
13 |
| - double minDiff = Double.MAX_VALUE; |
14 |
| - helper(root, target, ans, minDiff); |
15 |
| - return ans[0]; |
16 |
| - } |
| 18 | + double[] result = {Double.MAX_VALUE, -1}; |
| 19 | + helper(root, target, result); |
| 20 | + return (int) result[1]; |
| 21 | + } |
17 | 22 |
|
18 |
| - private void helper(TreeNode root, double target, int[] ans, double minDiff) { |
| 23 | + private void helper(TreeNode root, double target, double[] result) { |
19 | 24 | if (root == null) {
|
20 | 25 | return;
|
21 | 26 | }
|
22 |
| - if (Math.abs(root.val - target) < minDiff) { |
23 |
| - minDiff = Math.abs(root.val - target); |
24 |
| - ans[0] = root.val; |
25 |
| - } |
26 |
| - if (root.val < target) { |
27 |
| - helper(root.right, target, ans, minDiff); |
| 27 | + double diff = Math.abs(root.val - target); |
| 28 | + if (diff <= result[0]) { |
| 29 | + result[0] = diff; |
| 30 | + result[1] = root.val; |
28 | 31 | }
|
29 |
| - else { |
30 |
| - helper(root.left, target, ans, minDiff); |
| 32 | + if (root.val > target) { |
| 33 | + helper(root.left, target, result); |
| 34 | + } else { |
| 35 | + helper(root.right, target, result); |
31 | 36 | }
|
32 | 37 | }
|
33 | 38 | }
|
0 commit comments