-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaBST.java
More file actions
66 lines (58 loc) · 1.68 KB
/
Copy pathaBST.java
File metadata and controls
66 lines (58 loc) · 1.68 KB
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
import java.util.*;
public class aBST
{
public Integer Tree []; // массив ключей
public aBST(int depth)
{
// правильно рассчитайте размер массива для дерева глубины depth:
int tree_size = (int) (Math.pow(2, depth+1)-1);
Tree = new Integer[ tree_size ];
for(int i=0; i<tree_size; i++) Tree[i] = null;
}
public Integer FindKeyIndex(int key)
{
// ищем в массиве индекс ключа
for (int i = 0; i < Tree.length;){
if (Tree[i] == null){
return -i;
}
else if (Tree[i] == key){
return i;
}
else if (Tree[i] < key){
i = 2*i+2;
}
else if (Tree[i] > key){
i = 2*i+1;
}
}
return null; // не найден
}
public int AddKey(int key)
{
// добавляем ключ в массив
for (int i = 0; i < Tree.length;){
if (Tree[i] == null){
Tree[i] = key;
return i;
}
else if (Tree[i] == key){
return i;
}
else if (Tree[i] > key){
i = 2*i+1;
}
else if (Tree[i] < key){
i = 2*i+2;
}
}
// индекс добавленного/существующего ключа или -1 если не удалось
return -1;
}
public void printArray(){
for (Integer i : Tree){
System.out.print(i + " ");
}
System.out.println();
}
}