-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathb+tree.js
113 lines (113 loc) · 2.95 KB
/
b+tree.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
class btree{
constructor(data,limit){
this.data=[data];
this.left=null;
this.right=null;
this.limit=limit;
}
insert(data){
if(this.data.length<this.limit){
this.data.push(data);
this.data.sort((a,b)=>a-b);
}
else{
if(this.left==null){
this.left=new btree(data,this.limit);
}
else if(this.right==null){
this.right=new btree(data,this.limit);
}
else{
if(this.left.data.length<this.limit){
this.left.insert(data);
}
else if(this.right.data.length<this.limit){
this.right.insert(data);
}
else{
this.left.insert(data);
}
}
}
}
search(data){
if(this.data.includes(data)){
return true;
}
else{
if(this.left!=null && this.left.search(data)){
return true;
}
else if(this.right!=null && this.right.search(data)){
return true;
}
else{
return false;
}
}
}
delete(data){
if(this.data.includes(data)){
this.data.splice(this.data.indexOf(data),1);
if(this.left!=null){
this.data.push(this.left.data[0]);
this.data.sort((a,b)=>a-b);
this.left.delete(this.left.data[0]);
}
else if(this.right!=null){
this.data.push(this.right.data[0]);
this.data.sort((a,b)=>a-b);
this.right.delete(this.right.data[0]);
}
}
else{
if(this.left!=null){
this.left.delete(data);
}
else if(this.right!=null){
this.right.delete(data);
}
}
}
print(){
console.log(this.data);
if(this.left!=null){
this.left.print();
}
if(this.right!=null){
this.right.print();
}
}
depth(){
if(this.left==null && this.right==null){
return 0;
}
else if(this.left==null){
return this.right.depth()+1;
}
else if(this.right==null){
return this.left.depth()+1;
}
else{
return Math.max(this.left.depth(),this.right.depth())+1;
}
}
}
module.exports=
{
structure:btree,
description:"B-Tree",
complexity:{
insert:"O(log n)",
search:"O(log n)",
delete:"O(log n)"
},
category:"Tree",
methods:{
insert:"Inserts a new element into the tree",
search:"Searches for an element in the tree",
delete:"Deletes an element from the tree",
print:"Prints the tree",
depth:"Returns the depth of the tree"
}
};