Skip to content

Commit 001695a

Browse files
authored
Update Closest Binary Search Tree Value.java
1 parent b2188e0 commit 001695a

File tree

1 file changed

+20
-15
lines changed

1 file changed

+20
-15
lines changed

Easy/Closest Binary Search Tree Value.java

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,30 +4,35 @@
44
* int val;
55
* TreeNode left;
66
* 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+
* }
814
* }
915
*/
1016
class Solution {
1117
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+
}
1722

18-
private void helper(TreeNode root, double target, int[] ans, double minDiff) {
23+
private void helper(TreeNode root, double target, double[] result) {
1924
if (root == null) {
2025
return;
2126
}
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;
2831
}
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);
3136
}
3237
}
3338
}

0 commit comments

Comments
 (0)