Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2246403

Browse files
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

Lines changed: 32 additions & 0 deletions
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)

AltStyle によって変換されたページ (->オリジナル) /