-
Notifications
You must be signed in to change notification settings - Fork 0
/
ClosestValue.java
40 lines (38 loc) · 1.24 KB
/
ClosestValue.java
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
39
40
public class ClosestValue {
// 1. recursion
public int closestValue(TreeNode root, double target) {
return closest(root, target, root.val);
}
private int closest(TreeNode root, double target, int closest) {
if (Math.abs(target - closest) > Math.abs(target - root.val)) {
closest = root.val;
}
if (target < root.val && root.left != null) {
return closest(root.left, target, closest);
} else if (target > root.val && root.right != null) {
return closest(root.right, target, closest);
} else {
return closest;
}
}
// 2. iterative
public int closestValue1(TreeNode root, double target) {
return closest1(root, target, root.val);
}
private int closest1(TreeNode root, double target, int closest) {
TreeNode cur = root;
while (cur != null) {
if (Math.abs(target - closest) > Math.abs(target - cur.val)) {
closest = cur.val;
}
if (target < cur.val) {
cur = cur.left;
} else if (target > cur.val) {
cur = cur.right;
} else {
break;
}
return closest;
}
}
}