Debian Codegraph @

trees/btree/btree.go

raw symbols SCIP
1 // Copyright (c) 2015, Emir Pasic. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package btree implements a B tree.
6 //
7 // According to Knuth's definition, a B-tree of order m is a tree which satisfies the following properties:
8 // - Every node has at most m children.
9 // - Every non-leaf node (except root) has at least ⌈m/2⌉ children.
10 // - The root has at least two children if it is not a leaf node.
11 // - A non-leaf node with k children contains k−1 keys.
12 // - All leaves appear in the same level
13 //
14 // Structure is not thread safe.
15 //
16 // References: https://en.wikipedia.org/wiki/B-tree
17 package btree
18
19 import (
20 "bytes"
21 "cmp"
22 "fmt"
23 "strings"
24
25 "github.com/emirpasic/gods/v2/trees"
26 "github.com/emirpasic/gods/v2/utils"
27 )
28
29 // Assert Tree implementation
30 var _ trees.Tree[int] = (*Tree[string, int])(nil)
31
32 // Tree holds elements of the B-tree
33 type Tree[K comparable, V any] struct {
34 Root *Node[K, V] // Root node
35 Comparator utils.Comparator[K] // Key comparator
36 size int // Total number of keys in the tree
37 m int // order (maximum number of children)
38 }
39
40 // Node is a single element within the tree
41 type Node[K comparable, V any] struct {
42 Parent *Node[K, V]
43 Entries []*Entry[K, V] // Contained keys in node
44 Children []*Node[K, V] // Children nodes
45 }
46
47 // Entry represents the key-value pair contained within nodes
48 type Entry[K comparable, V any] struct {
49 Key K
50 Value V
51 }
52
53 // New instantiates a B-tree with the order (maximum number of children) and the built-in comparator for K
54 func New[K cmp.Ordered, V any](order int) *Tree[K, V] {
55 return NewWith[K, V](order, cmp.Compare[K])
56 }
57
58 // NewWith instantiates a B-tree with the order (maximum number of children) and a custom key comparator.
59 func NewWith[K comparable, V any](order int, comparator utils.Comparator[K]) *Tree[K, V] {
60 if order < 3 {
61 panic("Invalid order, should be at least 3")
62 }
63 return &Tree[K, V]{m: order, Comparator: comparator}
64 }
65
66 // Put inserts key-value pair node into the tree.
67 // If key already exists, then its value is updated with the new value.
68 // Key should adhere to the comparator's type assertion, otherwise method panics.
69 func (tree *Tree[K, V]) Put(key K, value V) {
70 entry := &Entry[K, V]{Key: key, Value: value}
71
72 if tree.Root == nil {
73 tree.Root = &Node[K, V]{Entries: []*Entry[K, V]{entry}, Children: []*Node[K, V]{}}
74 tree.size++
75 return
76 }
77
78 if tree.insert(tree.Root, entry) {
79 tree.size++
80 }
81 }
82
83 // Get searches the node in the tree by key and returns its value or nil if key is not found in tree.
84 // Second return parameter is true if key was found, otherwise false.
85 // Key should adhere to the comparator's type assertion, otherwise method panics.
86 func (tree *Tree[K, V]) Get(key K) (value V, found bool) {
87 node, index, found := tree.searchRecursively(tree.Root, key)
88 if found {
89 return node.Entries[index].Value, true
90 }
91 return value, false
92 }
93
94 // GetNode searches the node in the tree by key and returns its node or nil if key is not found in tree.
95 // Key should adhere to the comparator's type assertion, otherwise method panics.
96 func (tree *Tree[K, V]) GetNode(key K) *Node[K, V] {
97 node, _, _ := tree.searchRecursively(tree.Root, key)
98 return node
99 }
100
101 // Remove remove the node from the tree by key.
102 // Key should adhere to the comparator's type assertion, otherwise method panics.
103 func (tree *Tree[K, V]) Remove(key K) {
104 node, index, found := tree.searchRecursively(tree.Root, key)
105 if found {
106 tree.delete(node, index)
107 tree.size--
108 }
109 }
110
111 // Empty returns true if tree does not contain any nodes
112 func (tree *Tree[K, V]) Empty() bool {
113 return tree.size == 0
114 }
115
116 // Size returns number of nodes in the tree.
117 func (tree *Tree[K, V]) Size() int {
118 return tree.size
119 }
120
121 // Size returns the number of elements stored in the subtree.
122 // Computed dynamically on each call, i.e. the subtree is traversed to count the number of the nodes.
123 func (node *Node[K, V]) Size() int {
124 if node == nil {
125 return 0
126 }
127 size := 1
128 for _, child := range node.Children {
129 size += child.Size()
130 }
131 return size
132 }
133
134 // Keys returns all keys in-order
135 func (tree *Tree[K, V]) Keys() []K {
136 keys := make([]K, tree.size)
137 it := tree.Iterator()
138 for i := 0; it.Next(); i++ {
139 keys[i] = it.Key()
140 }
141 return keys
142 }
143
144 // Values returns all values in-order based on the key.
145 func (tree *Tree[K, V]) Values() []V {
146 values := make([]V, tree.size)
147 it := tree.Iterator()
148 for i := 0; it.Next(); i++ {
149 values[i] = it.Value()
150 }
151 return values
152 }
153
154 // Clear removes all nodes from the tree.
155 func (tree *Tree[K, V]) Clear() {
156 tree.Root = nil
157 tree.size = 0
158 }
159
160 // Height returns the height of the tree.
161 func (tree *Tree[K, V]) Height() int {
162 return tree.Root.height()
163 }
164
165 // Left returns the left-most (min) node or nil if tree is empty.
166 func (tree *Tree[K, V]) Left() *Node[K, V] {
167 return tree.left(tree.Root)
168 }
169
170 // LeftKey returns the left-most (min) key or nil if tree is empty.
171 func (tree *Tree[K, V]) LeftKey() interface{} {
172 if left := tree.Left(); left != nil {
173 return left.Entries[0].Key
174 }
175 return nil
176 }
177
178 // LeftValue returns the left-most value or nil if tree is empty.
179 func (tree *Tree[K, V]) LeftValue() interface{} {
180 if left := tree.Left(); left != nil {
181 return left.Entries[0].Value
182 }
183 return nil
184 }
185
186 // Right returns the right-most (max) node or nil if tree is empty.
187 func (tree *Tree[K, V]) Right() *Node[K, V] {
188 return tree.right(tree.Root)
189 }
190
191 // RightKey returns the right-most (max) key or nil if tree is empty.
192 func (tree *Tree[K, V]) RightKey() interface{} {
193 if right := tree.Right(); right != nil {
194 return right.Entries[len(right.Entries)-1].Key
195 }
196 return nil
197 }
198
199 // RightValue returns the right-most value or nil if tree is empty.
200 func (tree *Tree[K, V]) RightValue() interface{} {
201 if right := tree.Right(); right != nil {
202 return right.Entries[len(right.Entries)-1].Value
203 }
204 return nil
205 }
206
207 // String returns a string representation of container (for debugging purposes)
208 func (tree *Tree[K, V]) String() string {
209 var buffer bytes.Buffer
210 buffer.WriteString("BTree\n")
211 if !tree.Empty() {
212 tree.output(&buffer, tree.Root, 0)
213 }
214 return buffer.String()
215 }
216
217 func (entry *Entry[K, V]) String() string {
218 return fmt.Sprintf("%v", entry.Key)
219 }
220
221 func (tree *Tree[K, V]) output(buffer *bytes.Buffer, node *Node[K, V], level int) {
222 for e := 0; e < len(node.Entries)+1; e++ {
223 if e < len(node.Children) {
224 tree.output(buffer, node.Children[e], level+1)
225 }
226 if e < len(node.Entries) {
227 buffer.WriteString(strings.Repeat(" ", level))
228 buffer.WriteString(fmt.Sprintf("%v", node.Entries[e].Key) + "\n")
229 }
230 }
231 }
232
233 func (node *Node[K, V]) height() int {
234 height := 0
235 for ; node != nil; node = node.Children[0] {
236 height++
237 if len(node.Children) == 0 {
238 break
239 }
240 }
241 return height
242 }
243
244 func (tree *Tree[K, V]) isLeaf(node *Node[K, V]) bool {
245 return len(node.Children) == 0
246 }
247
248 func (tree *Tree[K, V]) isFull(node *Node[K, V]) bool {
249 return len(node.Entries) == tree.maxEntries()
250 }
251
252 func (tree *Tree[K, V]) shouldSplit(node *Node[K, V]) bool {
253 return len(node.Entries) > tree.maxEntries()
254 }
255
256 func (tree *Tree[K, V]) maxChildren() int {
257 return tree.m
258 }
259
260 func (tree *Tree[K, V]) minChildren() int {
261 return (tree.m + 1) / 2 // ceil(m/2)
262 }
263
264 func (tree *Tree[K, V]) maxEntries() int {
265 return tree.maxChildren() - 1
266 }
267
268 func (tree *Tree[K, V]) minEntries() int {
269 return tree.minChildren() - 1
270 }
271
272 func (tree *Tree[K, V]) middle() int {
273 return (tree.m - 1) / 2 // "-1" to favor right nodes to have more keys when splitting
274 }
275
276 // search searches only within the single node among its entries
277 func (tree *Tree[K, V]) search(node *Node[K, V], key K) (index int, found bool) {
278 low, high := 0, len(node.Entries)-1
279 var mid int
280 for low <= high {
281 mid = (high + low) / 2
282 compare := tree.Comparator(key, node.Entries[mid].Key)
283 switch {
284 case compare > 0:
285 low = mid + 1
286 case compare < 0:
287 high = mid - 1
288 case compare == 0:
289 return mid, true
290 }
291 }
292 return low, false
293 }
294
295 // searchRecursively searches recursively down the tree starting at the startNode
296 func (tree *Tree[K, V]) searchRecursively(startNode *Node[K, V], key K) (node *Node[K, V], index int, found bool) {
297 if tree.Empty() {
298 return nil, -1, false
299 }
300 node = startNode
301 for {
302 index, found = tree.search(node, key)
303 if found {
304 return node, index, true
305 }
306 if tree.isLeaf(node) {
307 return nil, -1, false
308 }
309 node = node.Children[index]
310 }
311 }
312
313 func (tree *Tree[K, V]) insert(node *Node[K, V], entry *Entry[K, V]) (inserted bool) {
314 if tree.isLeaf(node) {
315 return tree.insertIntoLeaf(node, entry)
316 }
317 return tree.insertIntoInternal(node, entry)
318 }
319
320 func (tree *Tree[K, V]) insertIntoLeaf(node *Node[K, V], entry *Entry[K, V]) (inserted bool) {
321 insertPosition, found := tree.search(node, entry.Key)
322 if found {
323 node.Entries[insertPosition] = entry
324 return false
325 }
326 // Insert entry's key in the middle of the node
327 node.Entries = append(node.Entries, nil)
328 copy(node.Entries[insertPosition+1:], node.Entries[insertPosition:])
329 node.Entries[insertPosition] = entry
330 tree.split(node)
331 return true
332 }
333
334 func (tree *Tree[K, V]) insertIntoInternal(node *Node[K, V], entry *Entry[K, V]) (inserted bool) {
335 insertPosition, found := tree.search(node, entry.Key)
336 if found {
337 node.Entries[insertPosition] = entry
338 return false
339 }
340 return tree.insert(node.Children[insertPosition], entry)
341 }
342
343 func (tree *Tree[K, V]) split(node *Node[K, V]) {
344 if !tree.shouldSplit(node) {
345 return
346 }
347
348 if node == tree.Root {
349 tree.splitRoot()
350 return
351 }
352
353 tree.splitNonRoot(node)
354 }
355
356 func (tree *Tree[K, V]) splitNonRoot(node *Node[K, V]) {
357 middle := tree.middle()
358 parent := node.Parent
359
360 left := &Node[K, V]{Entries: append([]*Entry[K, V](nil), node.Entries[:middle]...), Parent: parent}
361 right := &Node[K, V]{Entries: append([]*Entry[K, V](nil), node.Entries[middle+1:]...), Parent: parent}
362
363 // Move children from the node to be split into left and right nodes
364 if !tree.isLeaf(node) {
365 left.Children = append([]*Node[K, V](nil), node.Children[:middle+1]...)
366 right.Children = append([]*Node[K, V](nil), node.Children[middle+1:]...)
367 setParent(left.Children, left)
368 setParent(right.Children, right)
369 }
370
371 insertPosition, _ := tree.search(parent, node.Entries[middle].Key)
372
373 // Insert middle key into parent
374 parent.Entries = append(parent.Entries, nil)
375 copy(parent.Entries[insertPosition+1:], parent.Entries[insertPosition:])
376 parent.Entries[insertPosition] = node.Entries[middle]
377
378 // Set child left of inserted key in parent to the created left node
379 parent.Children[insertPosition] = left
380
381 // Set child right of inserted key in parent to the created right node
382 parent.Children = append(parent.Children, nil)
383 copy(parent.Children[insertPosition+2:], parent.Children[insertPosition+1:])
384 parent.Children[insertPosition+1] = right
385
386 tree.split(parent)
387 }
388
389 func (tree *Tree[K, V]) splitRoot() {
390 middle := tree.middle()
391
392 left := &Node[K, V]{Entries: append([]*Entry[K, V](nil), tree.Root.Entries[:middle]...)}
393 right := &Node[K, V]{Entries: append([]*Entry[K, V](nil), tree.Root.Entries[middle+1:]...)}
394
395 // Move children from the node to be split into left and right nodes
396 if !tree.isLeaf(tree.Root) {
397 left.Children = append([]*Node[K, V](nil), tree.Root.Children[:middle+1]...)
398 right.Children = append([]*Node[K, V](nil), tree.Root.Children[middle+1:]...)
399 setParent(left.Children, left)
400 setParent(right.Children, right)
401 }
402
403 // Root is a node with one entry and two children (left and right)
404 newRoot := &Node[K, V]{
405 Entries: []*Entry[K, V]{tree.Root.Entries[middle]},
406 Children: []*Node[K, V]{left, right},
407 }
408
409 left.Parent = newRoot
410 right.Parent = newRoot
411 tree.Root = newRoot
412 }
413
414 func setParent[K comparable, V any](nodes []*Node[K, V], parent *Node[K, V]) {
415 for _, node := range nodes {
416 node.Parent = parent
417 }
418 }
419
420 func (tree *Tree[K, V]) left(node *Node[K, V]) *Node[K, V] {
421 if tree.Empty() {
422 return nil
423 }
424 current := node
425 for {
426 if tree.isLeaf(current) {
427 return current
428 }
429 current = current.Children[0]
430 }
431 }
432
433 func (tree *Tree[K, V]) right(node *Node[K, V]) *Node[K, V] {
434 if tree.Empty() {
435 return nil
436 }
437 current := node
438 for {
439 if tree.isLeaf(current) {
440 return current
441 }
442 current = current.Children[len(current.Children)-1]
443 }
444 }
445
446 // leftSibling returns the node's left sibling and child index (in parent) if it exists, otherwise (nil,-1)
447 // key is any of keys in node (could even be deleted).
448 func (tree *Tree[K, V]) leftSibling(node *Node[K, V], key K) (*Node[K, V], int) {
449 if node.Parent != nil {
450 index, _ := tree.search(node.Parent, key)
451 index--
452 if index >= 0 && index < len(node.Parent.Children) {
453 return node.Parent.Children[index], index
454 }
455 }
456 return nil, -1
457 }
458
459 // rightSibling returns the node's right sibling and child index (in parent) if it exists, otherwise (nil,-1)
460 // key is any of keys in node (could even be deleted).
461 func (tree *Tree[K, V]) rightSibling(node *Node[K, V], key K) (*Node[K, V], int) {
462 if node.Parent != nil {
463 index, _ := tree.search(node.Parent, key)
464 index++
465 if index < len(node.Parent.Children) {
466 return node.Parent.Children[index], index
467 }
468 }
469 return nil, -1
470 }
471
472 // delete deletes an entry in node at entries' index
473 // ref.: https://en.wikipedia.org/wiki/B-tree#Deletion
474 func (tree *Tree[K, V]) delete(node *Node[K, V], index int) {
475 // deleting from a leaf node
476 if tree.isLeaf(node) {
477 deletedKey := node.Entries[index].Key
478 tree.deleteEntry(node, index)
479 tree.rebalance(node, deletedKey)
480 if len(tree.Root.Entries) == 0 {
481 tree.Root = nil
482 }
483 return
484 }
485
486 // deleting from an internal node
487 leftLargestNode := tree.right(node.Children[index]) // largest node in the left sub-tree (assumed to exist)
488 leftLargestEntryIndex := len(leftLargestNode.Entries) - 1
489 node.Entries[index] = leftLargestNode.Entries[leftLargestEntryIndex]
490 deletedKey := leftLargestNode.Entries[leftLargestEntryIndex].Key
491 tree.deleteEntry(leftLargestNode, leftLargestEntryIndex)
492 tree.rebalance(leftLargestNode, deletedKey)
493 }
494
495 // rebalance rebalances the tree after deletion if necessary and returns true, otherwise false.
496 // Note that we first delete the entry and then call rebalance, thus the passed deleted key as reference.
497 func (tree *Tree[K, V]) rebalance(node *Node[K, V], deletedKey K) {
498 // check if rebalancing is needed
499 if node == nil || len(node.Entries) >= tree.minEntries() {
500 return
501 }
502
503 // try to borrow from left sibling
504 leftSibling, leftSiblingIndex := tree.leftSibling(node, deletedKey)
505 if leftSibling != nil && len(leftSibling.Entries) > tree.minEntries() {
506 // rotate right
507 node.Entries = append([]*Entry[K, V]{node.Parent.Entries[leftSiblingIndex]}, node.Entries...) // prepend parent's separator entry to node's entries
508 node.Parent.Entries[leftSiblingIndex] = leftSibling.Entries[len(leftSibling.Entries)-1]
509 tree.deleteEntry(leftSibling, len(leftSibling.Entries)-1)
510 if !tree.isLeaf(leftSibling) {
511 leftSiblingRightMostChild := leftSibling.Children[len(leftSibling.Children)-1]
512 leftSiblingRightMostChild.Parent = node
513 node.Children = append([]*Node[K, V]{leftSiblingRightMostChild}, node.Children...)
514 tree.deleteChild(leftSibling, len(leftSibling.Children)-1)
515 }
516 return
517 }
518
519 // try to borrow from right sibling
520 rightSibling, rightSiblingIndex := tree.rightSibling(node, deletedKey)
521 if rightSibling != nil && len(rightSibling.Entries) > tree.minEntries() {
522 // rotate left
523 node.Entries = append(node.Entries, node.Parent.Entries[rightSiblingIndex-1]) // append parent's separator entry to node's entries
524 node.Parent.Entries[rightSiblingIndex-1] = rightSibling.Entries[0]
525 tree.deleteEntry(rightSibling, 0)
526 if !tree.isLeaf(rightSibling) {
527 rightSiblingLeftMostChild := rightSibling.Children[0]
528 rightSiblingLeftMostChild.Parent = node
529 node.Children = append(node.Children, rightSiblingLeftMostChild)
530 tree.deleteChild(rightSibling, 0)
531 }
532 return
533 }
534
535 // merge with siblings
536 if rightSibling != nil {
537 // merge with right sibling
538 node.Entries = append(node.Entries, node.Parent.Entries[rightSiblingIndex-1])
539 node.Entries = append(node.Entries, rightSibling.Entries...)
540 deletedKey = node.Parent.Entries[rightSiblingIndex-1].Key
541 tree.deleteEntry(node.Parent, rightSiblingIndex-1)
542 tree.appendChildren(node.Parent.Children[rightSiblingIndex], node)
543 tree.deleteChild(node.Parent, rightSiblingIndex)
544 } else if leftSibling != nil {
545 // merge with left sibling
546 entries := append([]*Entry[K, V](nil), leftSibling.Entries...)
547 entries = append(entries, node.Parent.Entries[leftSiblingIndex])
548 node.Entries = append(entries, node.Entries...)
549 deletedKey = node.Parent.Entries[leftSiblingIndex].Key
550 tree.deleteEntry(node.Parent, leftSiblingIndex)
551 tree.prependChildren(node.Parent.Children[leftSiblingIndex], node)
552 tree.deleteChild(node.Parent, leftSiblingIndex)
553 }
554
555 // make the merged node the root if its parent was the root and the root is empty
556 if node.Parent == tree.Root && len(tree.Root.Entries) == 0 {
557 tree.Root = node
558 node.Parent = nil
559 return
560 }
561
562 // parent might underflow, so try to rebalance if necessary
563 tree.rebalance(node.Parent, deletedKey)
564 }
565
566 func (tree *Tree[K, V]) prependChildren(fromNode *Node[K, V], toNode *Node[K, V]) {
567 children := append([]*Node[K, V](nil), fromNode.Children...)
568 toNode.Children = append(children, toNode.Children...)
569 setParent(fromNode.Children, toNode)
570 }
571
572 func (tree *Tree[K, V]) appendChildren(fromNode *Node[K, V], toNode *Node[K, V]) {
573 toNode.Children = append(toNode.Children, fromNode.Children...)
574 setParent(fromNode.Children, toNode)
575 }
576
577 func (tree *Tree[K, V]) deleteEntry(node *Node[K, V], index int) {
578 copy(node.Entries[index:], node.Entries[index+1:])
579 node.Entries[len(node.Entries)-1] = nil
580 node.Entries = node.Entries[:len(node.Entries)-1]
581 }
582
583 func (tree *Tree[K, V]) deleteChild(node *Node[K, V], index int) {
584 if index >= len(node.Children) {
585 return
586 }
587 copy(node.Children[index:], node.Children[index+1:])
588 node.Children[len(node.Children)-1] = nil
589 node.Children = node.Children[:len(node.Children)-1]
590 }