AuD
Lecture 'Algorithmen und Datenstrukturen' (code examples)
BTree.java
Go to the documentation of this file.
1package aud;
2
4
9public class BTree<Key extends Comparable<Key>> implements Graphvizable {
10
11 KTreeNode<Key> root_;
12 int m_;
13
15 public BTree(int m) {
16 root_=new KTreeNode<Key>();
17 m_=m;
18 assert(m_>0);
19 }
20
22 public KTreeNode<Key> root() { return root_; }
23
25 public int getOrder() { return 2*m_+1; }
26
31 public Key find(Key key) {
32 return root_.find(key);
33 }
34
38 public boolean insert(Key key) {
39 return insert(root_,key);
40 }
41
52 protected void split(KTreeNode<Key> node) {
53 if (node.getK()>2*m_+1) { // CHEATING: we created and split a (2*m+2)-node!
54
55 onSplit(node);
56
57 node.split(m_+1);
58
59 if (node.parent_!=null) {
60 int i=node.parent_.getIndexOfChild(node);
61 assert (i>=0);
62 node.parent_.mergeChild(i);
63 node.parent_.checkConsistency();
64
65 split(node.parent_); // eventually split parent
66 }
67 }
68 }
69
71 protected void onSplit(KTreeNode<Key> node) {
72 }
73
75 protected boolean insert(KTreeNode<Key> node, Key key) {
76 // recursive find/insert (similar to KTreeNode#find)
77 for (int i=1; i<node.getK(); ++i) {
78 int cmp=node.compareKeys(key,node.getKey(i));
79 if (cmp==0)
80 return false; // key exists in tree
81 else if (cmp<0) {
82 if (node.getChild(i-1)==null) {
83
84 node.insert(key,i-1);
85 split(node);
86 return true;
87
88 } else
89 return insert(node.getChild(i-1),key); // recursive find
90 }
91 }
92
93 KTreeNode<Key> right=node.getChild(node.getK()-1);
94 if (right!=null)
95 return insert(right,key); // recursive find
96
97 node.insert(key,node.getK()-1);
98 split(node);
99
100 return true;
101 }
102
103 @Override
104 public String toDot() {
105 return root_.toDot();
106 }
107
110 public String toTikZ() {
111 return root_.toTikZ();
112 }
113
114 @Override public String toString() {
115 return root_.toString();
116 }
117
121 public void checkConsistency() {
122 // missing: check particular properties of 2-3-4-tree!
123 root_.checkConsistency();
124 }
125
127 public static void main(String[] args) {
128 BTree<Integer> tree=new BTree<Integer>(1);
129
130 int data[]={1,5,2,6,7,4,8,3};
131
132 for (int i : data) {
133 tree.insert(i);
134 System.out.println(tree.toTikZ()+"\n");
135 }
136
137 aud.util.DotViewer.displayWindow(tree,"B-tree");
138 }
139}
Simple viewer for Graphvizable.
Definition: DotViewer.java:48
static DotViewer displayWindow(Graphvizable object, String caption)
create new DotViewer (toplevel window) and display object
Definition: DotViewer.java:140
Interface for GraphViz rendering.
utilities (not related to AuD lecture)
Definition: Colormap.java:1
AuD lecture: Data structures, algorithms, examples.
Definition: A234Tree.java:1