-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbstContains.js
112 lines (94 loc) · 2.47 KB
/
bstContains.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
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
}
else{
let current=this.root
while(true){
if(value<current.value){
if(!current.left){
current.left=newNode
return
}current=current.left
}else if(value<current.value){
if(!this.right){
this.right=newNode
return
}current=current.right
}
}
}
}
contains(current,value){
if(current==null){
return false
}else{
if(current.value===value){
return true
}
else if(value<current.value){
this.contains(current.left,value)
}
else{
this.contains(current.right,value)
}
}
}
remove(value){
this.root=this.removeNode(this.root,value)
}
removeNode(current,value){
if(current===null){
return current
}
if(value<current.value){
this.removeNode(current.left,value)
}else if(value>current.value){
this.removeNode(current.right,value)
}
else{
if(!current.left&&!current.right){
return null
}
if(!current.left){
return current.right
}
if(!current.right){
return current.left
}
root.value=this.minimum(current.right)
current.right=this.removeNode(current.right,current.value)
}
return current
}
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
}
}