Question:
Give a BST, find a node whose value is closest to the target.
public static int closestValue(Node root, int value, int maxDiff) {
if (root == null) return Integer.MAX_VALUE;
int tempDiff = Math.abs(root.value - value);
// this statement prevents from further comparison once the closest node is found;
if (tempDiff >= maxDiff) return maxDiff;
if (root.value < tempDiff) {
return min(tempDiff, closestValue(root.right, value));
} else {
return min(tempDiff, closestValue(root.left, value));
}
}
Note: when call this method, the maxDiff is Integer.MAX_VALUE.