Skip to content

Commit f420047

Browse files
authored
Update 270-closest-binary-search-tree-value.js
1 parent db413f6 commit f420047

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

270-closest-binary-search-tree-value.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,17 @@ Output: 4
3535
* @param {number} target
3636
* @return {number}
3737
*/
38+
const closestValue = function(root, target) {
39+
const child = target < root.val ? root.left : root.right;
40+
if (!child) return root.val;
41+
const closest = closestValue(child, target);
42+
return Math.abs(closest - target) < Math.abs(root.val - target)
43+
? closest
44+
: root.val;
45+
};
46+
47+
// another
48+
3849
const closestValue = function(root, target) {
3950
if(root == null) return -1
4051
let node = root

0 commit comments

Comments
 (0)