-
Notifications
You must be signed in to change notification settings - Fork 156
/
Copy pathclosest-binary-search-tree-value.js
53 lines (43 loc) · 1.09 KB
/
closest-binary-search-tree-value.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
*
* Note:
* Given target value is a floating point.
* You are guaranteed to have only one unique value in the BST that is closest to the target.
*/
/**
* Iterative
*
* @param {TreeNode} root
* @param {number} target
* @return {number}
*/
const closestValue = (root, target) => {
let closest = root.val;
while (root) {
if (Math.abs(root.val - target) < Math.abs(closest - target)) {
closest = root.val;
}
if (root.val === target) {
break;
}
root = target > root.val ? root.right : root.left;
}
return closest;
};
/**
* Recursion
*
* @param {TreeNode} root
* @param {number} target
* @return {number}
*/
const closestValueR = (root, target) => {
const child = target < root.val ? root.left : root.right;
if (!child) {
return root.val;
}
const closest = closestValueR(child, target);
return Math.abs(target - closest) < Math.abs(target - root.val) ? closest : root.val;
};
export { closestValue, closestValueR };