-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBTree.java
64 lines (56 loc) · 1.75 KB
/
BTree.java
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
/**
* A B+ tree
*
* Como as estruturas e comportamentos dos nos internos e externos sao diferentes,
* existem classes diferentes para cada um
* @param <TKey> o tipo da chave
* @param <TValue> o tipo do valor
*/
public class BTree<TKey extends Comparable<TKey>, TValue> {
private BTreeNode<TKey> root;
public BTree() {
this.root = new BTreeLeafNode<TKey, TValue>();
}
/**
* Insere uma nova chave e valor na arvore
*/
public void insert(TKey key, TValue value) {
BTreeLeafNode<TKey, TValue> leaf = this.findLeafNodeShouldContainKey(key);
leaf.insertKey(key, value);
if (leaf.isOverflow()) {
BTreeNode<TKey> n = leaf.dealOverflow();
if (n != null)
this.root = n;
}
}
/**
* pesquisa por chave na arvore e retorna seu valor associado
*/
public TValue search(TKey key) {
BTreeLeafNode<TKey, TValue> leaf = this.findLeafNodeShouldContainKey(key);
int index = leaf.search(key);
return (index == -1) ? null : leaf.getValue(index); //percorre de forma recursiva
}
/**
* deleta uma chave e seu valor associado com a chave
*/
public void delete(TKey key) {
BTreeLeafNode<TKey, TValue> leaf = this.findLeafNodeShouldContainKey(key);
if (leaf.delete(key) && leaf.isUnderflow()) {
BTreeNode<TKey> n = leaf.dealUnderflow();
if (n != null)
this.root = n;
}
}
/**
procura no nó da folha qual deveria conter a chave
*/
@SuppressWarnings("unchecked")
private BTreeLeafNode<TKey, TValue> findLeafNodeShouldContainKey(TKey key) {
BTreeNode<TKey> node = this.root;
while (node.getNodeType() == TreeNodeType.InnerNode) {
node = ((BTreeInnerNode<TKey>)node).getChild( node.search(key) );
}
return (BTreeLeafNode<TKey, TValue>)node;
}
}