Skip to content

Commit db413f6

Browse files
authored
Create 270-closest-binary-search-tree-value.js
1 parent 2e7a2d6 commit db413f6

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
3+
Given a non-empty binary search tree and a target value,
4+
find the value in the BST that is closest to the target.
5+
6+
Note:
7+
8+
Given target value is a floating point.
9+
You are guaranteed to have only one unique value
10+
in the BST that is closest to the target.
11+
12+
Example:
13+
14+
Input: root = [4,2,5,1,3], target = 3.714286
15+
16+
4
17+
/ \
18+
2 5
19+
/ \
20+
1 3
21+
22+
Output: 4
23+
24+
*/
25+
26+
/**
27+
* Definition for a binary tree node.
28+
* function TreeNode(val) {
29+
* this.val = val;
30+
* this.left = this.right = null;
31+
* }
32+
*/
33+
/**
34+
* @param {TreeNode} root
35+
* @param {number} target
36+
* @return {number}
37+
*/
38+
const closestValue = function(root, target) {
39+
if(root == null) return -1
40+
let node = root
41+
const stack = []
42+
const res = []
43+
const K = 1
44+
while(node || stack.length) {
45+
if(node) {
46+
stack.push(node)
47+
node = node.left
48+
} else {
49+
node = stack.pop()
50+
if(res.length === K) {
51+
if(Math.abs(res[0] - target) < Math.abs(node.val - target)) {
52+
return res[0]
53+
}
54+
res.shift()
55+
}
56+
res.push(node.val)
57+
node = node.right
58+
}
59+
}
60+
return res[0]
61+
};

0 commit comments

Comments
 (0)