Skip to content

Commit 2246403

Browse files
committed
Closest Binary Search Tree Value
1 parent 73f57f5 commit 2246403

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

0270_closestBinarySearchTreeValue.js

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* @typedef {Object} TreeNode
3+
* @description Definition for a binary tree node.
4+
* @example
5+
* function TreeNode(val, left, right) {
6+
* this.val = (val===undefined ? 0 : val)
7+
* this.left = (left===undefined ? null : left)
8+
* this.right = (right===undefined ? null : right)
9+
* }
10+
*/
11+
12+
/**
13+
* @param {TreeNode} root Root of a binary tree.
14+
* @param {number} target Target value to find.
15+
* @return {number} Value of a node closest to target
16+
* @summary Closest Binary Search Tree Value {@link https://leetcode.com/problems/closest-binary-search-tree-value/}
17+
* @description Given a binary tree and target, find node with closest value.
18+
* Space O(1) - Constant number of variables created.
19+
* Time O(h) - for height of the tree.
20+
*/
21+
const closestValue = (root, target) => {
22+
let node = root;
23+
closest = root.val;
24+
25+
while (node !== null) {
26+
if (Math.abs(node.val - target) < Math.abs(closest - target)) closest = node.val;
27+
28+
node = target > node.val ? node.right : node.left;
29+
}
30+
31+
return closest;
32+
};

0 commit comments

Comments
 (0)