-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBinarySearch.java
More file actions
38 lines (37 loc) · 965 Bytes
/
BinarySearch.java
File metadata and controls
38 lines (37 loc) · 965 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Given a non-empty binary search tree and a target value
* find the value in the BST that is closest to the target.
* @author xinwang
*
*/
public class BinarySearch {
int goal;
double min = Double.MAX_VALUE;
public class TreeNode {
int val;
TreeNode left, right;
TreeNode(int value) {
val = value;
left = null;
right = null;
}
}
public int closestValue(TreeNode root, double target) {
searchHelper(root, target);
return goal;
}
private void searchHelper(TreeNode root, double target) {
if (root == null) {
return;
}
if (Math.abs(root.val - target) < min) {
min = Math.abs(root.val - target);
goal = root.val;
}
if (target < root.val) {
searchHelper(root.left, target);
} else {
searchHelper(root.right, target);
}
}
}