-
-
Notifications
You must be signed in to change notification settings - Fork 81
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
31 additions
and
0 deletions.
There are no files selected for viewing
31 changes: 31 additions & 0 deletions
31
coding_interviews/algoexpert/find-closest-value-in-bst/find-closest-value-in-bst.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |