-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbstClosest.js
87 lines (71 loc) · 1.75 KB
/
bstClosest.js
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
class node{
constructor(value){
this.value=value
this.left=null
this.right=null
}
}
class binaryTree{
constructor(){
this.root=null
}
insert(value){
let newNode=new node(value)
if(!this.root){
this.root=newNode
return this
}
let current=this.root
while(true){
if(value===current.value){
return this
}
else if(value<current.value){
if(!current.left){
current.left=newNode
return this
}
current=current.left
}else{
if(!current.right){
current.right=newNode
return this
}
current=current.right
}
}
}
closest(target){
let close=Infinity
let current=this.root
while(current){
if(Math.abs(target-current.value)<Math.abs(target-close)){
close=current.value
}
if(target<current.value){
current=current.left
}else if(target>current.value){
current=current.right
}else{
return close
}
}
return close
}
inorder(current){
if(current!=null){
this.inorder(current.left)
console.log(current.value)
this.inorder(current.right)
}
}
}
let bt=new binaryTree
bt.insert(50)
bt.insert(25)
bt.insert(75)
bt.insert(15)
bt.insert(35)
bt.insert(45)
console.log(bt.closest(70));
bt.inorder(bt.root)