-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathBTree.cs
More file actions
768 lines (668 loc) · 21.3 KB
/
BTree.cs
File metadata and controls
768 lines (668 loc) · 21.3 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
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
namespace DataStructures.BTree;
/// <summary>
/// A self-balancing search tree data structure that maintains sorted data
/// and allows searches, sequential access, insertions, and deletions in
/// logarithmic time.
/// </summary>
/// <remarks>
/// A B-Tree is a generalization of a binary search tree in which a node
/// can have more than two children. Unlike self-balancing binary search
/// trees, the B-Tree is optimized for systems that read and write large
/// blocks of data. It is commonly used in databases and file systems.
///
/// Properties of a B-Tree of minimum degree t:
/// 1. Every node has at most 2t-1 keys.
/// 2. Every node (except root) has at least t-1 keys.
/// 3. The root has at least 1 key (if tree is not empty).
/// 4. All leaves are at the same level.
/// 5. A non-leaf node with k keys has k+1 children.
///
/// Time Complexity:
/// - Search: O(log n)
/// - Insert: O(log n)
/// - Delete: O(log n)
///
/// Space Complexity: O(n)
///
/// See https://en.wikipedia.org/wiki/B-tree for more information.
/// Visualizer: https://www.cs.usfca.edu/~galles/visualization/BTree.html.
/// </remarks>
/// <typeparam name="TKey">Type of key for the tree.</typeparam>
public class BTree<TKey>
{
/// <summary>
/// Gets the number of keys in the tree.
/// </summary>
public int Count { get; private set; }
/// <summary>
/// Gets the minimum degree (t) of the B-Tree.
/// Each node can contain at most 2t-1 keys and at least t-1 keys (except root).
/// </summary>
public int MinimumDegree { get; }
/// <summary>
/// Comparer to use when comparing key values.
/// </summary>
private readonly Comparer<TKey> comparer;
/// <summary>
/// Reference to the root node.
/// </summary>
private BTreeNode<TKey>? root;
/// <summary>
/// Initializes a new instance of the <see cref="BTree{TKey}"/>
/// class with the specified minimum degree.
/// </summary>
/// <param name="minimumDegree">
/// Minimum degree (t) of the B-Tree. Must be at least 2.
/// Each node can contain at most 2t-1 keys.
/// </param>
/// <exception cref="ArgumentException">
/// Thrown when minimumDegree is less than 2.
/// </exception>
public BTree(int minimumDegree = 2)
{
if (minimumDegree < 2)
{
throw new ArgumentException("Minimum degree must be at least 2.", nameof(minimumDegree));
}
MinimumDegree = minimumDegree;
comparer = Comparer<TKey>.Default;
}
/// <summary>
/// Initializes a new instance of the <see cref="BTree{TKey}"/>
/// class with the specified minimum degree and custom comparer.
/// </summary>
/// <param name="minimumDegree">
/// Minimum degree (t) of the B-Tree. Must be at least 2.
/// </param>
/// <param name="customComparer">
/// Comparer to use when comparing keys.
/// </param>
/// <exception cref="ArgumentException">
/// Thrown when minimumDegree is less than 2.
/// </exception>
public BTree(int minimumDegree, Comparer<TKey> customComparer)
{
if (minimumDegree < 2)
{
throw new ArgumentException("Minimum degree must be at least 2.", nameof(minimumDegree));
}
MinimumDegree = minimumDegree;
comparer = customComparer;
}
/// <summary>
/// Add a single key to the tree.
/// </summary>
/// <param name="key">Key value to add.</param>
public void Add(TKey key)
{
if (root is null)
{
root = new BTreeNode<TKey>(MinimumDegree, true);
root.InsertKey(0, key);
Count++;
return;
}
if (root.IsFull())
{
var newRoot = new BTreeNode<TKey>(MinimumDegree, false);
newRoot.InsertChild(0, root);
SplitChild(newRoot, 0);
root = newRoot;
}
InsertNonFull(root, key);
Count++;
}
/// <summary>
/// Add multiple keys to the tree.
/// </summary>
/// <param name="keys">Key values to add.</param>
public void AddRange(IEnumerable<TKey> keys)
{
foreach (var key in keys)
{
Add(key);
}
}
/// <summary>
/// Remove a key from the tree.
/// </summary>
/// <param name="key">Key value to remove.</param>
/// <exception cref="KeyNotFoundException">
/// Thrown when the key is not found in the tree.
/// </exception>
public void Remove(TKey key)
{
if (root is null)
{
throw new KeyNotFoundException($"""Key "{key}" is not in the B-Tree.""");
}
Remove(root, key);
if (root.KeyCount == 0)
{
root = root.IsLeaf ? null : root.Children[0];
}
Count--;
}
/// <summary>
/// Check if given key is in the tree.
/// </summary>
/// <param name="key">Key value to search for.</param>
/// <returns>Whether or not the key is in the tree.</returns>
public bool Contains(TKey key)
{
return Search(root, key) is not null;
}
/// <summary>
/// Get the minimum key in the tree.
/// </summary>
/// <returns>Minimum key in tree.</returns>
/// <exception cref="InvalidOperationException">
/// Thrown when the tree is empty.
/// </exception>
public TKey GetMin()
{
if (root is null)
{
throw new InvalidOperationException("B-Tree is empty.");
}
return GetMin(root);
}
/// <summary>
/// Get the maximum key in the tree.
/// </summary>
/// <returns>Maximum key in tree.</returns>
/// <exception cref="InvalidOperationException">
/// Thrown when the tree is empty.
/// </exception>
public TKey GetMax()
{
if (root is null)
{
throw new InvalidOperationException("B-Tree is empty.");
}
return GetMax(root);
}
/// <summary>
/// Get keys in order from smallest to largest as defined by the
/// comparer.
/// </summary>
/// <returns>Keys in tree in order from smallest to largest.</returns>
public IEnumerable<TKey> GetKeysInOrder()
{
List<TKey> result = [];
InOrderTraversal(root);
return result;
void InOrderTraversal(BTreeNode<TKey>? node)
{
if (node is null)
{
return;
}
for (var i = 0; i < node.KeyCount; i++)
{
if (!node.IsLeaf)
{
InOrderTraversal(node.Children[i]);
}
result.Add(node.Keys[i]);
}
if (!node.IsLeaf)
{
InOrderTraversal(node.Children[node.KeyCount]);
}
}
}
/// <summary>
/// Get keys in the pre-order order.
/// </summary>
/// <returns>Keys in pre-order order.</returns>
public IEnumerable<TKey> GetKeysPreOrder()
{
var result = new List<TKey>();
PreOrderTraversal(root);
return result;
void PreOrderTraversal(BTreeNode<TKey>? node)
{
if (node is null)
{
return;
}
for (var i = 0; i < node.KeyCount; i++)
{
result.Add(node.Keys[i]);
}
if (!node.IsLeaf)
{
for (var i = 0; i <= node.KeyCount; i++)
{
PreOrderTraversal(node.Children[i]);
}
}
}
}
/// <summary>
/// Get keys in the post-order order.
/// </summary>
/// <returns>Keys in the post-order order.</returns>
public IEnumerable<TKey> GetKeysPostOrder()
{
var result = new List<TKey>();
PostOrderTraversal(root);
return result;
void PostOrderTraversal(BTreeNode<TKey>? node)
{
if (node is null)
{
return;
}
if (!node.IsLeaf)
{
for (var i = 0; i <= node.KeyCount; i++)
{
PostOrderTraversal(node.Children[i]);
}
}
for (var i = 0; i < node.KeyCount; i++)
{
result.Add(node.Keys[i]);
}
}
}
/// <summary>
/// Search for a key in the subtree rooted at the given node.
/// </summary>
/// <param name="node">Root of the subtree to search.</param>
/// <param name="key">Key to search for.</param>
/// <returns>Node containing the key, or null if not found.</returns>
private BTreeNode<TKey>? Search(BTreeNode<TKey>? node, TKey key)
{
if (node is null)
{
return null;
}
var i = 0;
while (i < node.KeyCount && comparer.Compare(key, node.Keys[i]) > 0)
{
i++;
}
if (i < node.KeyCount && comparer.Compare(key, node.Keys[i]) == 0)
{
return node;
}
if (node.IsLeaf)
{
return null;
}
return Search(node.Children[i], key);
}
/// <summary>
/// Insert a key into a non-full node.
/// </summary>
/// <param name="node">Node to insert the key into.</param>
/// <param name="key">Key to insert.</param>
/// <exception cref="ArgumentException">
/// Thrown when the key already exists in the tree.
/// </exception>
private void InsertNonFull(BTreeNode<TKey> node, TKey key)
{
if (node.IsLeaf)
{
InsertIntoLeaf(node, key);
}
else
{
InsertIntoNonLeaf(node, key);
}
}
/// <summary>
/// Insert a key into a leaf node.
/// </summary>
/// <param name="node">Leaf node to insert into.</param>
/// <param name="key">Key to insert.</param>
private void InsertIntoLeaf(BTreeNode<TKey> node, TKey key)
{
var i = node.KeyCount - 1;
while (i >= 0 && comparer.Compare(key, node.Keys[i]) < 0)
{
node.Keys[i + 1] = node.Keys[i];
i--;
}
if (i >= 0 && comparer.Compare(key, node.Keys[i]) == 0)
{
throw new ArgumentException($"""Key "{key}" already exists in B-Tree.""");
}
node.Keys[i + 1] = key;
node.KeyCount++;
}
/// <summary>
/// Insert a key into a non-leaf node.
/// </summary>
/// <param name="node">Non-leaf node to insert into.</param>
/// <param name="key">Key to insert.</param>
private void InsertIntoNonLeaf(BTreeNode<TKey> node, TKey key)
{
var i = FindInsertionIndex(node, key);
if (node.Children[i]!.IsFull())
{
SplitChild(node, i);
if (comparer.Compare(key, node.Keys[i]) > 0)
{
i++;
}
}
InsertNonFull(node.Children[i]!, key);
}
/// <summary>
/// Find the index where a key should be inserted in a non-leaf node.
/// </summary>
/// <param name="node">Node to search in.</param>
/// <param name="key">Key to insert.</param>
/// <returns>Index where the key should be inserted.</returns>
private int FindInsertionIndex(BTreeNode<TKey> node, TKey key)
{
var i = node.KeyCount - 1;
while (i >= 0 && comparer.Compare(key, node.Keys[i]) < 0)
{
i--;
}
if (i >= 0 && comparer.Compare(key, node.Keys[i]) == 0)
{
throw new ArgumentException($"""Key "{key}" already exists in B-Tree.""");
}
return i + 1;
}
/// <summary>
/// Split a full child of a node.
/// </summary>
/// <param name="parent">Parent node.</param>
/// <param name="childIndex">Index of the child to split.</param>
private void SplitChild(BTreeNode<TKey> parent, int childIndex)
{
var fullChild = parent.Children[childIndex]!;
var newChild = new BTreeNode<TKey>(MinimumDegree, fullChild.IsLeaf);
var midIndex = MinimumDegree - 1;
for (var j = 0; j < MinimumDegree - 1; j++)
{
newChild.Keys[j] = fullChild.Keys[j + MinimumDegree];
newChild.KeyCount++;
}
if (!fullChild.IsLeaf)
{
for (var j = 0; j < MinimumDegree; j++)
{
newChild.Children[j] = fullChild.Children[j + MinimumDegree];
}
}
fullChild.KeyCount = MinimumDegree - 1;
for (var j = parent.KeyCount; j > childIndex; j--)
{
parent.Children[j + 1] = parent.Children[j];
}
parent.Children[childIndex + 1] = newChild;
for (var j = parent.KeyCount - 1; j >= childIndex; j--)
{
parent.Keys[j + 1] = parent.Keys[j];
}
parent.Keys[childIndex] = fullChild.Keys[midIndex];
parent.KeyCount++;
}
/// <summary>
/// Remove a key from the subtree rooted at the given node.
/// </summary>
/// <param name="node">Root of the subtree.</param>
/// <param name="key">Key to remove.</param>
/// <exception cref="KeyNotFoundException">
/// Thrown when the key is not found in the subtree.
/// </exception>
private void Remove(BTreeNode<TKey> node, TKey key)
{
var idx = FindKey(node, key);
if (idx < node.KeyCount && comparer.Compare(node.Keys[idx], key) == 0)
{
if (node.IsLeaf)
{
RemoveFromLeaf(node, idx);
}
else
{
RemoveFromNonLeaf(node, idx);
}
}
else
{
if (node.IsLeaf)
{
throw new KeyNotFoundException($"""Key "{key}" is not in the B-Tree.""");
}
var isInSubtree = idx == node.KeyCount;
if (node.Children[idx]!.KeyCount < MinimumDegree)
{
Fill(node, idx);
}
if (isInSubtree && idx > node.KeyCount)
{
Remove(node.Children[idx - 1]!, key);
}
else
{
Remove(node.Children[idx]!, key);
}
}
}
/// <summary>
/// Find the index of the first key greater than or equal to the given key.
/// </summary>
/// <param name="node">Node to search in.</param>
/// <param name="key">Key to find.</param>
/// <returns>Index of the first key >= key.</returns>
private int FindKey(BTreeNode<TKey> node, TKey key)
{
var idx = 0;
while (idx < node.KeyCount && comparer.Compare(node.Keys[idx], key) < 0)
{
idx++;
}
return idx;
}
/// <summary>
/// Remove a key from a leaf node.
/// </summary>
/// <param name="node">Leaf node to remove from.</param>
/// <param name="idx">Index of the key to remove.</param>
private void RemoveFromLeaf(BTreeNode<TKey> node, int idx)
{
node.RemoveKey(idx);
}
/// <summary>
/// Remove a key from a non-leaf node.
/// </summary>
/// <param name="node">Non-leaf node to remove from.</param>
/// <param name="idx">Index of the key to remove.</param>
private void RemoveFromNonLeaf(BTreeNode<TKey> node, int idx)
{
var key = node.Keys[idx];
if (node.Children[idx]!.KeyCount >= MinimumDegree)
{
var predecessor = GetPredecessor(node, idx);
node.Keys[idx] = predecessor;
Remove(node.Children[idx]!, predecessor);
}
else if (node.Children[idx + 1]!.KeyCount >= MinimumDegree)
{
var successor = GetSuccessor(node, idx);
node.Keys[idx] = successor;
Remove(node.Children[idx + 1]!, successor);
}
else
{
Merge(node, idx);
Remove(node.Children[idx]!, key);
}
}
/// <summary>
/// Get the predecessor key of the key at the given index.
/// </summary>
/// <param name="node">Node containing the key.</param>
/// <param name="idx">Index of the key.</param>
/// <returns>Predecessor key.</returns>
private TKey GetPredecessor(BTreeNode<TKey> node, int idx)
{
var current = node.Children[idx]!;
while (!current.IsLeaf)
{
current = current.Children[current.KeyCount]!;
}
return current.Keys[current.KeyCount - 1];
}
/// <summary>
/// Get the successor key of the key at the given index.
/// </summary>
/// <param name="node">Node containing the key.</param>
/// <param name="idx">Index of the key.</param>
/// <returns>Successor key.</returns>
private TKey GetSuccessor(BTreeNode<TKey> node, int idx)
{
var current = node.Children[idx + 1]!;
while (!current.IsLeaf)
{
current = current.Children[0]!;
}
return current.Keys[0];
}
/// <summary>
/// Fill a child node that has fewer than minimum degree - 1 keys.
/// </summary>
/// <param name="node">Parent node.</param>
/// <param name="idx">Index of the child to fill.</param>
private void Fill(BTreeNode<TKey> node, int idx)
{
if (idx != 0 && node.Children[idx - 1]!.KeyCount >= MinimumDegree)
{
BorrowFromPrevious(node, idx);
}
else if (idx != node.KeyCount && node.Children[idx + 1]!.KeyCount >= MinimumDegree)
{
BorrowFromNext(node, idx);
}
else
{
Merge(node, idx != node.KeyCount ? idx : idx - 1);
}
}
/// <summary>
/// Borrow a key from the previous sibling.
/// </summary>
/// <param name="node">Parent node.</param>
/// <param name="childIdx">Index of the child that needs a key.</param>
private void BorrowFromPrevious(BTreeNode<TKey> node, int childIdx)
{
var child = node.Children[childIdx]!;
var sibling = node.Children[childIdx - 1]!;
for (var i = child.KeyCount - 1; i >= 0; i--)
{
child.Keys[i + 1] = child.Keys[i];
}
if (!child.IsLeaf)
{
for (var i = child.KeyCount; i >= 0; i--)
{
child.Children[i + 1] = child.Children[i];
}
}
child.Keys[0] = node.Keys[childIdx - 1];
if (!child.IsLeaf)
{
child.Children[0] = sibling.Children[sibling.KeyCount];
}
node.Keys[childIdx - 1] = sibling.Keys[sibling.KeyCount - 1];
child.KeyCount++;
sibling.KeyCount--;
}
/// <summary>
/// Borrow a key from the next sibling.
/// </summary>
/// <param name="node">Parent node.</param>
/// <param name="childIdx">Index of the child that needs a key.</param>
private void BorrowFromNext(BTreeNode<TKey> node, int childIdx)
{
var child = node.Children[childIdx]!;
var sibling = node.Children[childIdx + 1]!;
child.Keys[child.KeyCount] = node.Keys[childIdx];
if (!child.IsLeaf)
{
child.Children[child.KeyCount + 1] = sibling.Children[0];
}
node.Keys[childIdx] = sibling.Keys[0];
for (var i = 1; i < sibling.KeyCount; i++)
{
sibling.Keys[i - 1] = sibling.Keys[i];
}
if (!sibling.IsLeaf)
{
for (var i = 1; i <= sibling.KeyCount; i++)
{
sibling.Children[i - 1] = sibling.Children[i];
}
}
child.KeyCount++;
sibling.KeyCount--;
}
/// <summary>
/// Merge a child with its sibling.
/// </summary>
/// <param name="node">Parent node.</param>
/// <param name="idx">Index of the child to merge.</param>
private void Merge(BTreeNode<TKey> node, int idx)
{
var child = node.Children[idx]!;
var sibling = node.Children[idx + 1]!;
child.Keys[MinimumDegree - 1] = node.Keys[idx];
for (var i = 0; i < sibling.KeyCount; i++)
{
child.Keys[i + MinimumDegree] = sibling.Keys[i];
}
if (!child.IsLeaf)
{
for (var i = 0; i <= sibling.KeyCount; i++)
{
child.Children[i + MinimumDegree] = sibling.Children[i];
}
}
for (var i = idx + 1; i < node.KeyCount; i++)
{
node.Keys[i - 1] = node.Keys[i];
}
for (var i = idx + 2; i <= node.KeyCount; i++)
{
node.Children[i - 1] = node.Children[i];
}
child.KeyCount += sibling.KeyCount + 1;
node.KeyCount--;
}
/// <summary>
/// Get the minimum key in the subtree rooted at the given node.
/// </summary>
/// <param name="node">Root of the subtree.</param>
/// <returns>Minimum key in the subtree.</returns>
private TKey GetMin(BTreeNode<TKey> node)
{
while (!node.IsLeaf)
{
node = node.Children[0]!;
}
return node.Keys[0];
}
/// <summary>
/// Get the maximum key in the subtree rooted at the given node.
/// </summary>
/// <param name="node">Root of the subtree.</param>
/// <returns>Maximum key in the subtree.</returns>
private TKey GetMax(BTreeNode<TKey> node)
{
while (!node.IsLeaf)
{
node = node.Children[node.KeyCount]!;
}
return node.Keys[node.KeyCount - 1];
}
}