-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0270_closestBinarySearchTreeValue.js
More file actions
32 lines (28 loc) · 1 KB
/
0270_closestBinarySearchTreeValue.js
File metadata and controls
32 lines (28 loc) · 1 KB
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
/**
* @typedef {Object} TreeNode
* @description Definition for a binary tree node.
* @example
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root Root of a binary tree.
* @param {number} target Target value to find.
* @return {number} Value of a node closest to target
* @summary Closest Binary Search Tree Value {@link https://leetcode.com/problems/closest-binary-search-tree-value/}
* @description Given a binary tree and target, find node with closest value.
* Space O(1) - Constant number of variables created.
* Time O(h) - for height of the tree.
*/
const closestValue = (root, target) => {
let node = root;
closest = root.val;
while (node !== null) {
if (Math.abs(node.val - target) < Math.abs(closest - target)) closest = node.val;
node = target > node.val ? node.right : node.left;
}
return closest;
};