Skip to content

Commit c7d2ea2

Browse files
committed
updated closestValueBST
1 parent c6fa8fa commit c7d2ea2

File tree

1 file changed

+20
-25
lines changed

1 file changed

+20
-25
lines changed

closestValueInBst.js

Lines changed: 20 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,24 @@
11
function findClosestValueInBst(tree, target) {
2-
// Write your code here.
2+
// Write your code here.
33
// compare the difference
4-
return findClosestValueInBstHelper(tree, target, tree.value);
4+
return findClosestValueInBstHelper(tree, target, tree.value);
5+
}
6+
7+
function findClosestValueInBstHelper(tree, target, closest) {
8+
if (tree === null) {
9+
return closest;
510
}
6-
7-
function findClosestValueInBstHelper(tree, target, closest){
8-
if(!tree){
9-
return closest
10-
}
11-
if(Math.abs(target-closest)>Math.abs(target-tree.value){
12-
closest=tree.value
13-
}
14-
if(target<tree.value){
15-
return findClosestValueInBstHelper(tree.left, target, closest)
16-
}
17-
else if(taeget>tree.value){
18-
return findClosestValueInBstHelper(tree.right, target, closest)
19-
}
20-
else {
21-
return closest
22-
}
11+
if (Math.abs(target - closest) > Math.abs(target - tree.value)) {
12+
closest = tree.value;
2313
}
24-
25-
26-
27-
// Do not edit the line below.
28-
exports.findClosestValueInBst = findClosestValueInBst;
29-
14+
if (target < tree.value) {
15+
return findClosestValueInBstHelper(tree.left, target, closest);
16+
} else if (target > tree.value) {
17+
return findClosestValueInBstHelper(tree.right, target, closest);
18+
} else {
19+
return closest;
20+
}
21+
}
22+
23+
// Do not edit the line below.
24+
exports.findClosestValueInBst = findClosestValueInBst;

0 commit comments

Comments
 (0)