-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathClosestValue.java
More file actions
33 lines (32 loc) · 884 Bytes
/
Copy pathClosestValue.java
File metadata and controls
33 lines (32 loc) · 884 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
package leetcode;
public class ClosestValue {
double closest=Double.MAX_VALUE;
TreeNode closeNode = null;
public int closestValue(TreeNode root, double target) {
traverse(root,target);
return closeNode.val;
}
public void traverse(TreeNode root,double target){
if(root == null) return;
if(closest > Math.abs(root.val-target)){
closest = Math.abs(root.val-target);
closeNode = root;
}
if(target < root.val){
traverse(root.left, target);
}
else if(target == root.val){
return;
}
else{
traverse(root.right, target);
}
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.right = new TreeNode(100);
root.right.left = new TreeNode(4);
ClosestValue cv = new ClosestValue();
System.out.println(cv.closestValue(root,4.132));
}
}