KarmaAndCoding: Find the closest value to K in BST
Given (i) a non-empty binary search tree with double values (e.g. 3.5) in each node and (ii) a key value K. Write a method to find the closest value to K.
Code input/output:
printing inorder of BST:
3.3 3.49 3.51 3.52 3.55 3.56 3.57 3.59 3.62 3.65
Closest to 3.559: 3.56
Read full article from KarmaAndCoding: Find the closest value to K in BST
Given (i) a non-empty binary search tree with double values (e.g. 3.5) in each node and (ii) a key value K. Write a method to find the closest value to K.
Code input/output:
printing inorder of BST:
3.3 3.49 3.51 3.52 3.55 3.56 3.57 3.59 3.62 3.65
Closest to 3.559: 3.56
public
static
Double findClosestK(Node node, Double K,
double
closestK) {
if
(
null
== node) {
return
null
; }
if
(node.data.compareTo(K) ==
0
) {
return
K;
}
if
((Math.abs(node.data - K)) < (Math.abs(K - closestK))) {
closestK = node.data;
}
if
((K.compareTo(node.data) <=
0
) && (
null
!= node.left)) {
closestK = findClosestK(node.left, K, closestK);
}
else
if
(
null
!= node.right){
closestK = findClosestK(node.right, K, closestK);
}
return
closestK;
}