Skip to content

Commit

Permalink
*
Browse files Browse the repository at this point in the history
  • Loading branch information
imteekay committed Dec 6, 2023
1 parent 4991065 commit 9d1263c
Showing 1 changed file with 31 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Runtime: O(N), where N = number of nodes in the tree
// Space: O(1)

function findClosestValueInBst(tree, target, closestValue = null) {
if (!tree) {
return closestValue;
}

let currentDiff = Math.abs(tree.value - target);
let diff = closestValue ? Math.abs(closestValue - target) : currentDiff;
let leftValue = findClosestValueInBst(
tree.left,
target,
currentDiff <= diff ? tree.value : closestValue
);
let rightValue = findClosestValueInBst(
tree.right,
target,
currentDiff <= diff ? tree.value : closestValue
);
let leftDiff = Math.abs(leftValue - target);
let rightDiff = Math.abs(rightValue - target);

if (currentDiff <= leftDiff && currentDiff <= rightDiff) {
return tree.value;
} else if (leftDiff <= rightDiff) {
return leftValue;
}

return rightValue;
}

0 comments on commit 9d1263c

Please sign in to comment.