-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbinary-search-tree.js
124 lines (116 loc) · 3.52 KB
/
binary-search-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
114
115
116
117
118
119
120
121
122
123
124
class Node{
constructor(data, left = null, right = null){
this.data = data;
this.left = left;
this.right = right;
}
}
class BinarySearchTree{
constructor(){
this.root = null;
}
add(data){
const node = this.root;
if(node == null){
this.root = new Node(data);
return;
}
else{
const searchTree = (node) => {
if(data < node.data){
if(node.left == null){
node.left = new Node(data);
return;
}
else if(node.left != null){
return searchTree(node.left)
}
}
else if(data > node.data){
if(node.right == null){
node.right = new Node(data);
return;
}
else if(node.right != null){
return searchTree(node.right);
}
}
else{
return null;
}
}
return searchTree(node);
}
}
min(){
let current = this.root;
while(current.left !== null)
current = current.left;
return current.data;
}
max(){
let current = this.root;
while(current.right !== null)
current = current.right;
return current.data
}
find(data){
let current = this.root;
while(current.data !== data){
if(data < current.data)
current = current.left;
else if (data > current.data)
current = current.right;
else if(data === null)
return null;
}
return current;
}
isPresent(data){
let current = this.root;
while(current.data != data){
if(data === current.data)
return true;
if(data > current.data)
current = current.right;
else
current = current.left;
}
return false;
}
remove(data){
const removeNode = (node, data) => {
if(node == null)
return null;
if(data == node.data){
//без потомков
if(!node.left && !node.right)
return null;
//без потомков справа
if(!node.right)
return node.left;
//без потомков слева
if(!node.left)
return node.right;
/*есть потомки с двух сторон*/
//выбираю самое малое число из правой ветки
let tempNode = node.right;
while(tempNode.left !== null)
tempNode = tempNode.left;
//ставлю на место удаленной ноды
node.data = tempNode.data;
node.right = removeData(node.right, tempNode.data);
return node;
}
else if(data < node.data){
node.left = removeNode(node.left, data);
return node;
}
else{
node.right = removeNode(node.right, data);
return node;
}
}
this.root = removeNode(this.root, data);
}
}