-
Notifications
You must be signed in to change notification settings - Fork 15
/
BTree.java
64 lines (55 loc) · 1.74 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
* Since the structures and behaviors between internal node and external node are different,
* so there are two different classes for each kind of node.
* @param <TKey> the data type of the key
* @param <TValue> the data type of the value
*/
public class BTree<TKey extends Comparable<TKey>, TValue> {
private BTreeNode<TKey> root;
public BTree() {
this.root = new BTreeLeafNode<TKey, TValue>();
}
/**
* Insert a new key and its associated value into the B+ tree.
*/
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;
}
}
/**
* Search a key value on the tree and return its associated value.
*/
public TValue search(TKey key) {
BTreeLeafNode<TKey, TValue> leaf = this.findLeafNodeShouldContainKey(key);
int index = leaf.search(key);
return (index == -1) ? null : leaf.getValue(index);
}
/**
* Delete a key and its associated value from the tree.
*/
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;
}
}
/**
* Search the leaf node which should contain the specified key
*/
@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;
}
}