-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbstFullOperations.js
155 lines (130 loc) · 3.3 KB
/
bstFullOperations.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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(!current.right){
current.right=newNode
return
}current=current.right
}
}
}
}
remove(value){
this.root=this.removeNode(this.root,value)
}
removeNode(current,value){
if(current.value===null){
return current
}
if(value<current.value){
current.left=this.removeNode(current.left,value)
}else if(value>current.value){
current.right= 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
}
minimum(current){
if(!current.left){
return current.value
}else{
this.minimum(current.left)
}
}
maximum(current){
if(!current.right){
return current.value
}
this.maximum(current.right)
}
contains(current,value){
if(current==null){
return false
}else{
if(current.value===value){
return true
}
else if(value<current.value){
return this.contains(current.left,value)
}else
{
return this.contains(current.right,value)
}
}
}
nearest(target){
let closest=Infinity
let current=this.root
while(current){
if(Math.abs(target-current.value)<Math.abs(target-closest)){
closest=current.value
}
if(target<current.value){
current=current.left
}else if(target>current.value){
current=current.right
}
else{
return closest
}
}
return closest
}
inorder(current){
if(current){
this.inorder(current.left)
console.log(current.value);
this.inorder(current.right)
}
}
preorder(current){
if(current){
console.log(current.value);
this.preorder(current.left)
this.preorder(current.right)
}
}
}
let bt=new binaryTree
bt.insert(20)
bt.insert(15)
bt.insert(25)
bt.remove(25)
console.log(bt.contains(bt.root,45));
console.log(bt.nearest(19));
bt.inorder(bt.root)