forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClosestBinarySearchTreeValue.java
More file actions
34 lines (29 loc) · 921 Bytes
/
ClosestBinarySearchTreeValue.java
File metadata and controls
34 lines (29 loc) · 921 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
public class ClosestBinarySearchTreeValue {
public int closestValue(TreeNode root, double target) {
int closest = root.val;
double min = Double.MAX_VALUE;
for (TreeNode p = root; p != null; ) {
double gap = Math.abs(target - p.val);
if (gap < min) {
min = gap;
closest = p.val;
}
if (target > p.val) {
p = p.right;
} else if (target < p.val) {
p = p.left;
} else {
break;
}
}
return closest;
}
/**
public int closestValue(TreeNode root, double target) {
int a = root.val;
TreeNode kid = target < a ? root.left : root.right;
if (kid == null) return a;
int b = closestValue(kid, target);
return Math.abs(a - target) < Math.abs(b - target) ? a : b;
}*/
}