-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathClosest_270.java
More file actions
45 lines (40 loc) · 1.16 KB
/
Closest_270.java
File metadata and controls
45 lines (40 loc) · 1.16 KB
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
41
42
43
44
45
class Closest_270 {
// Standard solution
public int closestValue(TreeNode root, double target) {
int res = root.val;
while (root != null) {
int val = root.val;
res = Math.abs(val - target) < Math.abs(res - target) ? val : res;
root = target < val ? root.left : root.right;
}
return res;
}
// My first solution
// Compare double with integer
/*
public int closestValue(TreeNode root, double target) {
int prev = Integer.MIN_VALUE;
int post = Integer.MAX_VALUE;
TreeNode node = root;
while (node != null) {
if (target > node.val) {
prev = node.val;
node = node.right;
} else if (target < node.val) {
post = node.val;
node = node.left;
} else {
return node.val;
}
}
int res = 0;
if (prev != Integer.MIN_VALUE)
res = prev;
else
return post;
if (post != Integer.MAX_VALUE && post - target < target - prev)
res = post;
return res;
}
*/
}