Skip to content

Instantly share code, notes, and snippets.

@jchiatt
Created November 2, 2020 16:46
Show Gist options
  • Save jchiatt/e5083d4e9ee620f6c1bf58945843aa37 to your computer and use it in GitHub Desktop.
Save jchiatt/e5083d4e9ee620f6c1bf58945843aa37 to your computer and use it in GitHub Desktop.
function findClosestValueInBst(tree, target) {
return findClosestValueRecursive(tree, target, tree.value);
}
function findClosestValueRecursive(tree, target, closest) {
if (!tree) return closest;
if (Math.abs(target - closest) > Math.abs(target - tree.value)) {
closest = tree.value;
}
if (target < tree.value) {
return findClosestValueRecursive(tree.left, target, closest);
}
if (target > tree.value) {
return findClosestValueRecursive(tree.right, target, closest);
}
return closest;
}
class BST {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment