-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution270.java
More file actions
46 lines (45 loc) · 1.33 KB
/
Solution270.java
File metadata and controls
46 lines (45 loc) · 1.33 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
46
public class Solution270 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Result {
double dist;
int val;
Result(double d, int v) {
dist = d;
val = v;
}
}
public int closestValue(TreeNode root, double target) {
Result result = new Result(Double.MAX_VALUE, root.val);
findClosestValue(root, target, result);
return result.val;
}
public void findClosestValue(TreeNode root, double target, Result result) {
if (root == null) {
return;
}
double diff = root.val - target;
if (Math.abs(diff) < result.dist) {
result.dist = Math.abs(diff);
result.val = root.val;
}
if (target < root.val) {
findClosestValue(root.left, target, result);
} else if (target > root.val) {
findClosestValue(root.right, target, result);
} else {
return;
}
}
public static void main(String args[]) {
Solution270 s = new Solution270();
TreeNode root = s.new TreeNode(1500000000);
root.left = s.new TreeNode(1400000000);
int diff = s.closestValue(root, -1500000000.0);
System.out.println(diff);
}
}