Prompt
Find Closest Value In BST
Write a function that takes in a Binary Search Tree (BST) and a target integer value and returns the closest value to that target value contained in the BST. You can assume that there will only be one closest value.
Each BST node has an integer value , a left child node, and a right child node. A node is said to be a valid BST
node if and only if it satises the BST property: its value is strictly greater than the values of every node to its left; its value is less than or equal to the values of every node to its right; and its children nodes are either valid BST nodes themselves or None / null .
Sample Input
Sample Output
13
Solution 1
import java.util.*;
class Program {
public static int findClosestValueInBst(BST tree, int target) {
// Write your code here.
return findClosestValueInBst(tree, target, Double.MAX_VALUE);//A
}
public static int findClosestValueInBst(BST tree, int target, double closest) {
if (Math.abs(target - closest) > Math.abs(target - tree.value)){
closest = tree.value;
}
if (target < tree.value && tree.left != null){//B
return findClosestValueInBst(tree.left, target, closest);
} else if (target > tree.value && tree.right != null){
return findClosestValueInBst(tree.right, target, closest);
} else {
return (int)closest;
}
}
static class BST {
public int value;
public BST left;
public BST right;
public BST(int value) {
this.value = value;
}
}
}
# 1A
Integer.MAX_VALU;
这里不可以用int,因为有溢出问题
如果target是-1,tree.value有[1,2 ,2147483647],那么会返回2147483647
原码,补码和反码原理
原码,补码和反码原理补充
# 1B
细品
Solution 2
import java.util.*;
class Program {
public static int findClosestValueInBst(BST tree, int target) {
// Write your code here.
return findClosestValueInBst(tree, target, Double.MAX_VALUE);
}
public static int findClosestValueInBst(BST tree, int target, double closest) {
BST currentNode = tree;
while (currentNode != null){
if (Math.abs(closest - target) > Math.abs(currentNode.value - target)){
closest = currentNode.value;
}
if (target < currentNode.value) {
currentNode = currentNode.left;
} else if (target > currentNode.value) {
currentNode = currentNode.right;
} else {
break;
}
}
return (int) closest;
}
static class BST {
public int value;
public BST left;
public BST right;
public BST(int value) {
this.value = value;
}
}
}