github.com/zhongdalu/gf@v1.0.0/g/container/gtree/gtree_btree.go (about) 1 // Copyright 2019 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/zhongdalu/gf. 6 7 package gtree 8 9 import ( 10 "bytes" 11 "encoding/json" 12 "fmt" 13 "strings" 14 15 "github.com/zhongdalu/gf/g/container/gvar" 16 "github.com/zhongdalu/gf/g/internal/rwmutex" 17 ) 18 19 // BTree holds elements of the B-tree. 20 type BTree struct { 21 mu *rwmutex.RWMutex 22 root *BTreeNode 23 comparator func(v1, v2 interface{}) int 24 size int // Total number of keys in the tree 25 m int // order (maximum number of children) 26 } 27 28 // BTreeNode is a single element within the tree. 29 type BTreeNode struct { 30 Parent *BTreeNode 31 Entries []*BTreeEntry // Contained keys in node 32 Children []*BTreeNode // Children nodes 33 } 34 35 // BTreeEntry represents the key-value pair contained within nodes. 36 type BTreeEntry struct { 37 Key interface{} 38 Value interface{} 39 } 40 41 // NewBTree instantiates a B-tree with <m> (maximum number of children) and a custom key comparator. 42 // The parameter <unsafe> used to specify whether using tree in un-concurrent-safety, 43 // which is false in default. 44 // Note that the <m> must be greater or equal than 3, or else it panics. 45 func NewBTree(m int, comparator func(v1, v2 interface{}) int, unsafe ...bool) *BTree { 46 if m < 3 { 47 panic("Invalid order, should be at least 3") 48 } 49 return &BTree{ 50 comparator: comparator, 51 mu: rwmutex.New(unsafe...), 52 m: m, 53 } 54 } 55 56 // NewBTreeFrom instantiates a B-tree with <m> (maximum number of children), a custom key comparator and data map. 57 // The parameter <unsafe> used to specify whether using tree in un-concurrent-safety, 58 // which is false in default. 59 func NewBTreeFrom(m int, comparator func(v1, v2 interface{}) int, data map[interface{}]interface{}, unsafe ...bool) *BTree { 60 tree := NewBTree(m, comparator, unsafe...) 61 for k, v := range data { 62 tree.doSet(k, v) 63 } 64 return tree 65 } 66 67 // Clone returns a new tree with a copy of current tree. 68 func (tree *BTree) Clone(unsafe ...bool) *BTree { 69 newTree := NewBTree(tree.m, tree.comparator, !tree.mu.IsSafe()) 70 newTree.Sets(tree.Map()) 71 return newTree 72 } 73 74 // Set inserts key-value item into the tree. 75 func (tree *BTree) Set(key interface{}, value interface{}) { 76 tree.mu.Lock() 77 defer tree.mu.Unlock() 78 tree.doSet(key, value) 79 } 80 81 // doSet inserts key-value pair node into the tree. 82 // If key already exists, then its value is updated with the new value. 83 func (tree *BTree) doSet(key interface{}, value interface{}) { 84 entry := &BTreeEntry{Key: key, Value: value} 85 if tree.root == nil { 86 tree.root = &BTreeNode{Entries: []*BTreeEntry{entry}, Children: []*BTreeNode{}} 87 tree.size++ 88 return 89 } 90 91 if tree.insert(tree.root, entry) { 92 tree.size++ 93 } 94 } 95 96 // Sets batch sets key-values to the tree. 97 func (tree *BTree) Sets(data map[interface{}]interface{}) { 98 tree.mu.Lock() 99 defer tree.mu.Unlock() 100 for k, v := range data { 101 tree.doSet(k, v) 102 } 103 } 104 105 // Get searches the node in the tree by <key> and returns its value or nil if key is not found in tree. 106 func (tree *BTree) Get(key interface{}) (value interface{}) { 107 value, _ = tree.Search(key) 108 return 109 } 110 111 // doSetWithLockCheck checks whether value of the key exists with mutex.Lock, 112 // if not exists, set value to the map with given <key>, 113 // or else just return the existing value. 114 // 115 // When setting value, if <value> is type of <func() interface {}>, 116 // it will be executed with mutex.Lock of the hash map, 117 // and its return value will be set to the map with <key>. 118 // 119 // It returns value with given <key>. 120 func (tree *BTree) doSetWithLockCheck(key interface{}, value interface{}) interface{} { 121 tree.mu.Lock() 122 defer tree.mu.Unlock() 123 if entry := tree.doSearch(key); entry != nil { 124 return entry.Value 125 } 126 if f, ok := value.(func() interface{}); ok { 127 value = f() 128 } 129 tree.doSet(key, value) 130 return value 131 } 132 133 // GetOrSet returns the value by key, 134 // or set value with given <value> if not exist and returns this value. 135 func (tree *BTree) GetOrSet(key interface{}, value interface{}) interface{} { 136 if v, ok := tree.Search(key); !ok { 137 return tree.doSetWithLockCheck(key, value) 138 } else { 139 return v 140 } 141 } 142 143 // GetOrSetFunc returns the value by key, 144 // or sets value with return value of callback function <f> if not exist 145 // and returns this value. 146 func (tree *BTree) GetOrSetFunc(key interface{}, f func() interface{}) interface{} { 147 if v, ok := tree.Search(key); !ok { 148 return tree.doSetWithLockCheck(key, f()) 149 } else { 150 return v 151 } 152 } 153 154 // GetOrSetFuncLock returns the value by key, 155 // or sets value with return value of callback function <f> if not exist 156 // and returns this value. 157 // 158 // GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function <f> 159 // with mutex.Lock of the hash map. 160 func (tree *BTree) GetOrSetFuncLock(key interface{}, f func() interface{}) interface{} { 161 if v, ok := tree.Search(key); !ok { 162 return tree.doSetWithLockCheck(key, f) 163 } else { 164 return v 165 } 166 } 167 168 // GetVar returns a gvar.Var with the value by given <key>. 169 // The returned gvar.Var is un-concurrent safe. 170 func (tree *BTree) GetVar(key interface{}) *gvar.Var { 171 return gvar.New(tree.Get(key), true) 172 } 173 174 // GetVarOrSet returns a gvar.Var with result from GetVarOrSet. 175 // The returned gvar.Var is un-concurrent safe. 176 func (tree *BTree) GetVarOrSet(key interface{}, value interface{}) *gvar.Var { 177 return gvar.New(tree.GetOrSet(key, value), true) 178 } 179 180 // GetVarOrSetFunc returns a gvar.Var with result from GetOrSetFunc. 181 // The returned gvar.Var is un-concurrent safe. 182 func (tree *BTree) GetVarOrSetFunc(key interface{}, f func() interface{}) *gvar.Var { 183 return gvar.New(tree.GetOrSetFunc(key, f), true) 184 } 185 186 // GetVarOrSetFuncLock returns a gvar.Var with result from GetOrSetFuncLock. 187 // The returned gvar.Var is un-concurrent safe. 188 func (tree *BTree) GetVarOrSetFuncLock(key interface{}, f func() interface{}) *gvar.Var { 189 return gvar.New(tree.GetOrSetFuncLock(key, f), true) 190 } 191 192 // SetIfNotExist sets <value> to the map if the <key> does not exist, then return true. 193 // It returns false if <key> exists, and <value> would be ignored. 194 func (tree *BTree) SetIfNotExist(key interface{}, value interface{}) bool { 195 if !tree.Contains(key) { 196 tree.doSetWithLockCheck(key, value) 197 return true 198 } 199 return false 200 } 201 202 // SetIfNotExistFunc sets value with return value of callback function <f>, then return true. 203 // It returns false if <key> exists, and <value> would be ignored. 204 func (tree *BTree) SetIfNotExistFunc(key interface{}, f func() interface{}) bool { 205 if !tree.Contains(key) { 206 tree.doSetWithLockCheck(key, f()) 207 return true 208 } 209 return false 210 } 211 212 // SetIfNotExistFuncLock sets value with return value of callback function <f>, then return true. 213 // It returns false if <key> exists, and <value> would be ignored. 214 // 215 // SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that 216 // it executes function <f> with mutex.Lock of the hash map. 217 func (tree *BTree) SetIfNotExistFuncLock(key interface{}, f func() interface{}) bool { 218 if !tree.Contains(key) { 219 tree.doSetWithLockCheck(key, f) 220 return true 221 } 222 return false 223 } 224 225 // Contains checks whether <key> exists in the tree. 226 func (tree *BTree) Contains(key interface{}) bool { 227 _, ok := tree.Search(key) 228 return ok 229 } 230 231 // Remove remove the node from the tree by key. 232 // Key should adhere to the comparator's type assertion, otherwise method panics. 233 func (tree *BTree) doRemove(key interface{}) (value interface{}) { 234 node, index, found := tree.searchRecursively(tree.root, key) 235 if found { 236 value = node.Entries[index].Value 237 tree.delete(node, index) 238 tree.size-- 239 } 240 return 241 } 242 243 // Remove removes the node from the tree by <key>. 244 func (tree *BTree) Remove(key interface{}) (value interface{}) { 245 tree.mu.Lock() 246 defer tree.mu.Unlock() 247 return tree.doRemove(key) 248 } 249 250 // Removes batch deletes values of the tree by <keys>. 251 func (tree *BTree) Removes(keys []interface{}) { 252 tree.mu.Lock() 253 defer tree.mu.Unlock() 254 for _, key := range keys { 255 tree.doRemove(key) 256 } 257 } 258 259 // Empty returns true if tree does not contain any nodes 260 func (tree *BTree) IsEmpty() bool { 261 return tree.Size() == 0 262 } 263 264 // Size returns number of nodes in the tree. 265 func (tree *BTree) Size() int { 266 tree.mu.RLock() 267 defer tree.mu.RUnlock() 268 return tree.size 269 } 270 271 // Keys returns all keys in asc order. 272 func (tree *BTree) Keys() []interface{} { 273 keys := make([]interface{}, tree.Size()) 274 index := 0 275 tree.IteratorAsc(func(key, value interface{}) bool { 276 keys[index] = key 277 index++ 278 return true 279 }) 280 return keys 281 } 282 283 // Values returns all values in asc order based on the key. 284 func (tree *BTree) Values() []interface{} { 285 values := make([]interface{}, tree.Size()) 286 index := 0 287 tree.IteratorAsc(func(key, value interface{}) bool { 288 values[index] = value 289 index++ 290 return true 291 }) 292 return values 293 } 294 295 // Map returns all key-value items as map. 296 func (tree *BTree) Map() map[interface{}]interface{} { 297 m := make(map[interface{}]interface{}, tree.Size()) 298 tree.IteratorAsc(func(key, value interface{}) bool { 299 m[key] = value 300 return true 301 }) 302 return m 303 } 304 305 // Clear removes all nodes from the tree. 306 func (tree *BTree) Clear() { 307 tree.mu.Lock() 308 defer tree.mu.Unlock() 309 tree.root = nil 310 tree.size = 0 311 } 312 313 // Height returns the height of the tree. 314 func (tree *BTree) Height() int { 315 tree.mu.RLock() 316 defer tree.mu.RUnlock() 317 return tree.root.height() 318 } 319 320 // Left returns the left-most (min) entry or nil if tree is empty. 321 func (tree *BTree) Left() *BTreeEntry { 322 tree.mu.RLock() 323 defer tree.mu.RUnlock() 324 node := tree.left(tree.root) 325 return node.Entries[0] 326 } 327 328 // Right returns the right-most (max) entry or nil if tree is empty. 329 func (tree *BTree) Right() *BTreeEntry { 330 tree.mu.RLock() 331 defer tree.mu.RUnlock() 332 node := tree.right(tree.root) 333 return node.Entries[len(node.Entries)-1] 334 } 335 336 // String returns a string representation of container (for debugging purposes) 337 func (tree *BTree) String() string { 338 tree.mu.RLock() 339 defer tree.mu.RUnlock() 340 var buffer bytes.Buffer 341 if _, err := buffer.WriteString("BTree\n"); err != nil { 342 } 343 if tree.size != 0 { 344 tree.output(&buffer, tree.root, 0, true) 345 } 346 return buffer.String() 347 } 348 349 // Search searches the tree with given <key>. 350 // Second return parameter <found> is true if key was found, otherwise false. 351 func (tree *BTree) Search(key interface{}) (value interface{}, found bool) { 352 tree.mu.RLock() 353 defer tree.mu.RUnlock() 354 node, index, found := tree.searchRecursively(tree.root, key) 355 if found { 356 return node.Entries[index].Value, true 357 } 358 return nil, false 359 } 360 361 // Search searches the tree with given <key> without mutex. 362 // It returns the entry if found or otherwise nil. 363 func (tree *BTree) doSearch(key interface{}) *BTreeEntry { 364 node, index, found := tree.searchRecursively(tree.root, key) 365 if found { 366 return node.Entries[index] 367 } 368 return nil 369 } 370 371 // Print prints the tree to stdout. 372 func (tree *BTree) Print() { 373 fmt.Println(tree.String()) 374 } 375 376 // Iterator is alias of IteratorAsc. 377 func (tree *BTree) Iterator(f func(key, value interface{}) bool) { 378 tree.IteratorAsc(f) 379 } 380 381 // IteratorAsc iterates the tree in ascending order with given callback function <f>. 382 // If <f> returns true, then it continues iterating; or false to stop. 383 func (tree *BTree) IteratorAsc(f func(key, value interface{}) bool) { 384 tree.mu.RLock() 385 defer tree.mu.RUnlock() 386 node := tree.left(tree.root) 387 if node == nil { 388 return 389 } 390 entry := node.Entries[0] 391 loop: 392 if entry == nil { 393 return 394 } 395 if !f(entry.Key, entry.Value) { 396 return 397 } 398 // Find current entry position in current node 399 e, _ := tree.search(node, entry.Key) 400 // Try to go down to the child right of the current entry 401 if e+1 < len(node.Children) { 402 node = node.Children[e+1] 403 // Try to go down to the child left of the current node 404 for len(node.Children) > 0 { 405 node = node.Children[0] 406 } 407 // Return the left-most entry 408 entry = node.Entries[0] 409 goto loop 410 } 411 // Above assures that we have reached a leaf node, so return the next entry in current node (if any) 412 if e+1 < len(node.Entries) { 413 entry = node.Entries[e+1] 414 goto loop 415 } 416 // Reached leaf node and there are no entries to the right of the current entry, so go up to the parent 417 for node.Parent != nil { 418 node = node.Parent 419 // Find next entry position in current node (note: search returns the first equal or bigger than entry) 420 e, _ := tree.search(node, entry.Key) 421 // Check that there is a next entry position in current node 422 if e < len(node.Entries) { 423 entry = node.Entries[e] 424 goto loop 425 } 426 } 427 } 428 429 // IteratorDesc iterates the tree in descending order with given callback function <f>. 430 // If <f> returns true, then it continues iterating; or false to stop. 431 func (tree *BTree) IteratorDesc(f func(key, value interface{}) bool) { 432 tree.mu.RLock() 433 defer tree.mu.RUnlock() 434 node := tree.right(tree.root) 435 if node == nil { 436 return 437 } 438 entry := node.Entries[len(node.Entries)-1] 439 loop: 440 if entry == nil { 441 return 442 } 443 if !f(entry.Key, entry.Value) { 444 return 445 } 446 // Find current entry position in current node 447 e, _ := tree.search(node, entry.Key) 448 // Try to go down to the child left of the current entry 449 if e < len(node.Children) { 450 node = node.Children[e] 451 // Try to go down to the child right of the current node 452 for len(node.Children) > 0 { 453 node = node.Children[len(node.Children)-1] 454 } 455 // Return the right-most entry 456 entry = node.Entries[len(node.Entries)-1] 457 goto loop 458 } 459 // Above assures that we have reached a leaf node, so return the previous entry in current node (if any) 460 if e-1 >= 0 { 461 entry = node.Entries[e-1] 462 goto loop 463 } 464 465 // Reached leaf node and there are no entries to the left of the current entry, so go up to the parent 466 for node.Parent != nil { 467 node = node.Parent 468 // Find previous entry position in current node (note: search returns the first equal or bigger than entry) 469 e, _ := tree.search(node, entry.Key) 470 // Check that there is a previous entry position in current node 471 if e-1 >= 0 { 472 entry = node.Entries[e-1] 473 goto loop 474 } 475 } 476 } 477 478 func (tree *BTree) output(buffer *bytes.Buffer, node *BTreeNode, level int, isTail bool) { 479 for e := 0; e < len(node.Entries)+1; e++ { 480 if e < len(node.Children) { 481 tree.output(buffer, node.Children[e], level+1, true) 482 } 483 if e < len(node.Entries) { 484 if _, err := buffer.WriteString(strings.Repeat(" ", level)); err != nil { 485 } 486 if _, err := buffer.WriteString(fmt.Sprintf("%v", node.Entries[e].Key) + "\n"); err != nil { 487 } 488 } 489 } 490 } 491 492 func (node *BTreeNode) height() int { 493 h := 0 494 n := node 495 for ; n != nil; n = n.Children[0] { 496 h++ 497 if len(n.Children) == 0 { 498 break 499 } 500 } 501 return h 502 } 503 504 func (tree *BTree) isLeaf(node *BTreeNode) bool { 505 return len(node.Children) == 0 506 } 507 508 //func (tree *BTree) isFull(node *BTreeNode) bool { 509 // return len(node.Entries) == tree.maxEntries() 510 //} 511 512 func (tree *BTree) shouldSplit(node *BTreeNode) bool { 513 return len(node.Entries) > tree.maxEntries() 514 } 515 516 func (tree *BTree) maxChildren() int { 517 return tree.m 518 } 519 520 func (tree *BTree) minChildren() int { 521 return (tree.m + 1) / 2 // ceil(m/2) 522 } 523 524 func (tree *BTree) maxEntries() int { 525 return tree.maxChildren() - 1 526 } 527 528 func (tree *BTree) minEntries() int { 529 return tree.minChildren() - 1 530 } 531 532 func (tree *BTree) middle() int { 533 // "-1" to favor right nodes to have more keys when splitting 534 return (tree.m - 1) / 2 535 } 536 537 // search searches only within the single node among its entries 538 func (tree *BTree) search(node *BTreeNode, key interface{}) (index int, found bool) { 539 low, mid, high := 0, 0, len(node.Entries)-1 540 for low <= high { 541 mid = (high + low) / 2 542 compare := tree.comparator(key, node.Entries[mid].Key) 543 switch { 544 case compare > 0: 545 low = mid + 1 546 case compare < 0: 547 high = mid - 1 548 case compare == 0: 549 return mid, true 550 } 551 } 552 return low, false 553 } 554 555 // searchRecursively searches recursively down the tree starting at the startNode 556 func (tree *BTree) searchRecursively(startNode *BTreeNode, key interface{}) (node *BTreeNode, index int, found bool) { 557 if tree.size == 0 { 558 return nil, -1, false 559 } 560 node = startNode 561 for { 562 index, found = tree.search(node, key) 563 if found { 564 return node, index, true 565 } 566 if tree.isLeaf(node) { 567 return nil, -1, false 568 } 569 node = node.Children[index] 570 } 571 } 572 573 func (tree *BTree) insert(node *BTreeNode, entry *BTreeEntry) (inserted bool) { 574 if tree.isLeaf(node) { 575 return tree.insertIntoLeaf(node, entry) 576 } 577 return tree.insertIntoInternal(node, entry) 578 } 579 580 func (tree *BTree) insertIntoLeaf(node *BTreeNode, entry *BTreeEntry) (inserted bool) { 581 insertPosition, found := tree.search(node, entry.Key) 582 if found { 583 node.Entries[insertPosition] = entry 584 return false 585 } 586 // Insert entry's key in the middle of the node 587 node.Entries = append(node.Entries, nil) 588 copy(node.Entries[insertPosition+1:], node.Entries[insertPosition:]) 589 node.Entries[insertPosition] = entry 590 tree.split(node) 591 return true 592 } 593 594 func (tree *BTree) insertIntoInternal(node *BTreeNode, entry *BTreeEntry) (inserted bool) { 595 insertPosition, found := tree.search(node, entry.Key) 596 if found { 597 node.Entries[insertPosition] = entry 598 return false 599 } 600 return tree.insert(node.Children[insertPosition], entry) 601 } 602 603 func (tree *BTree) split(node *BTreeNode) { 604 if !tree.shouldSplit(node) { 605 return 606 } 607 608 if node == tree.root { 609 tree.splitRoot() 610 return 611 } 612 613 tree.splitNonRoot(node) 614 } 615 616 func (tree *BTree) splitNonRoot(node *BTreeNode) { 617 middle := tree.middle() 618 parent := node.Parent 619 620 left := &BTreeNode{Entries: append([]*BTreeEntry(nil), node.Entries[:middle]...), Parent: parent} 621 right := &BTreeNode{Entries: append([]*BTreeEntry(nil), node.Entries[middle+1:]...), Parent: parent} 622 623 // Move children from the node to be split into left and right nodes 624 if !tree.isLeaf(node) { 625 left.Children = append([]*BTreeNode(nil), node.Children[:middle+1]...) 626 right.Children = append([]*BTreeNode(nil), node.Children[middle+1:]...) 627 setParent(left.Children, left) 628 setParent(right.Children, right) 629 } 630 631 insertPosition, _ := tree.search(parent, node.Entries[middle].Key) 632 633 // Insert middle key into parent 634 parent.Entries = append(parent.Entries, nil) 635 copy(parent.Entries[insertPosition+1:], parent.Entries[insertPosition:]) 636 parent.Entries[insertPosition] = node.Entries[middle] 637 638 // Set child left of inserted key in parent to the created left node 639 parent.Children[insertPosition] = left 640 641 // Set child right of inserted key in parent to the created right node 642 parent.Children = append(parent.Children, nil) 643 copy(parent.Children[insertPosition+2:], parent.Children[insertPosition+1:]) 644 parent.Children[insertPosition+1] = right 645 646 tree.split(parent) 647 } 648 649 func (tree *BTree) splitRoot() { 650 middle := tree.middle() 651 left := &BTreeNode{Entries: append([]*BTreeEntry(nil), tree.root.Entries[:middle]...)} 652 right := &BTreeNode{Entries: append([]*BTreeEntry(nil), tree.root.Entries[middle+1:]...)} 653 654 // Move children from the node to be split into left and right nodes 655 if !tree.isLeaf(tree.root) { 656 left.Children = append([]*BTreeNode(nil), tree.root.Children[:middle+1]...) 657 right.Children = append([]*BTreeNode(nil), tree.root.Children[middle+1:]...) 658 setParent(left.Children, left) 659 setParent(right.Children, right) 660 } 661 662 // Root is a node with one entry and two children (left and right) 663 newRoot := &BTreeNode{ 664 Entries: []*BTreeEntry{tree.root.Entries[middle]}, 665 Children: []*BTreeNode{left, right}, 666 } 667 668 left.Parent = newRoot 669 right.Parent = newRoot 670 tree.root = newRoot 671 } 672 673 func setParent(nodes []*BTreeNode, parent *BTreeNode) { 674 for _, node := range nodes { 675 node.Parent = parent 676 } 677 } 678 679 func (tree *BTree) left(node *BTreeNode) *BTreeNode { 680 if tree.size == 0 { 681 return nil 682 } 683 current := node 684 for { 685 if tree.isLeaf(current) { 686 return current 687 } 688 current = current.Children[0] 689 } 690 } 691 692 func (tree *BTree) right(node *BTreeNode) *BTreeNode { 693 if tree.size == 0 { 694 return nil 695 } 696 current := node 697 for { 698 if tree.isLeaf(current) { 699 return current 700 } 701 current = current.Children[len(current.Children)-1] 702 } 703 } 704 705 // leftSibling returns the node's left sibling and child index (in parent) if it exists, otherwise (nil,-1) 706 // key is any of keys in node (could even be deleted). 707 func (tree *BTree) leftSibling(node *BTreeNode, key interface{}) (*BTreeNode, int) { 708 if node.Parent != nil { 709 index, _ := tree.search(node.Parent, key) 710 index-- 711 if index >= 0 && index < len(node.Parent.Children) { 712 return node.Parent.Children[index], index 713 } 714 } 715 return nil, -1 716 } 717 718 // rightSibling returns the node's right sibling and child index (in parent) if it exists, otherwise (nil,-1) 719 // key is any of keys in node (could even be deleted). 720 func (tree *BTree) rightSibling(node *BTreeNode, key interface{}) (*BTreeNode, int) { 721 if node.Parent != nil { 722 index, _ := tree.search(node.Parent, key) 723 index++ 724 if index < len(node.Parent.Children) { 725 return node.Parent.Children[index], index 726 } 727 } 728 return nil, -1 729 } 730 731 // delete deletes an entry in node at entries' index 732 // ref.: https://en.wikipedia.org/wiki/B-tree#Deletion 733 func (tree *BTree) delete(node *BTreeNode, index int) { 734 // deleting from a leaf node 735 if tree.isLeaf(node) { 736 deletedKey := node.Entries[index].Key 737 tree.deleteEntry(node, index) 738 tree.rebalance(node, deletedKey) 739 if len(tree.root.Entries) == 0 { 740 tree.root = nil 741 } 742 return 743 } 744 745 // deleting from an internal node 746 leftLargestNode := tree.right(node.Children[index]) // largest node in the left sub-tree (assumed to exist) 747 leftLargestEntryIndex := len(leftLargestNode.Entries) - 1 748 node.Entries[index] = leftLargestNode.Entries[leftLargestEntryIndex] 749 deletedKey := leftLargestNode.Entries[leftLargestEntryIndex].Key 750 tree.deleteEntry(leftLargestNode, leftLargestEntryIndex) 751 tree.rebalance(leftLargestNode, deletedKey) 752 } 753 754 // rebalance rebalances the tree after deletion if necessary and returns true, otherwise false. 755 // Note that we first delete the entry and then call rebalance, thus the passed deleted key as reference. 756 func (tree *BTree) rebalance(node *BTreeNode, deletedKey interface{}) { 757 // check if rebalancing is needed 758 if node == nil || len(node.Entries) >= tree.minEntries() { 759 return 760 } 761 762 // try to borrow from left sibling 763 leftSibling, leftSiblingIndex := tree.leftSibling(node, deletedKey) 764 if leftSibling != nil && len(leftSibling.Entries) > tree.minEntries() { 765 // rotate right 766 node.Entries = append([]*BTreeEntry{node.Parent.Entries[leftSiblingIndex]}, node.Entries...) // prepend parent's separator entry to node's entries 767 node.Parent.Entries[leftSiblingIndex] = leftSibling.Entries[len(leftSibling.Entries)-1] 768 tree.deleteEntry(leftSibling, len(leftSibling.Entries)-1) 769 if !tree.isLeaf(leftSibling) { 770 leftSiblingRightMostChild := leftSibling.Children[len(leftSibling.Children)-1] 771 leftSiblingRightMostChild.Parent = node 772 node.Children = append([]*BTreeNode{leftSiblingRightMostChild}, node.Children...) 773 tree.deleteChild(leftSibling, len(leftSibling.Children)-1) 774 } 775 return 776 } 777 778 // try to borrow from right sibling 779 rightSibling, rightSiblingIndex := tree.rightSibling(node, deletedKey) 780 if rightSibling != nil && len(rightSibling.Entries) > tree.minEntries() { 781 // rotate left 782 node.Entries = append(node.Entries, node.Parent.Entries[rightSiblingIndex-1]) // append parent's separator entry to node's entries 783 node.Parent.Entries[rightSiblingIndex-1] = rightSibling.Entries[0] 784 tree.deleteEntry(rightSibling, 0) 785 if !tree.isLeaf(rightSibling) { 786 rightSiblingLeftMostChild := rightSibling.Children[0] 787 rightSiblingLeftMostChild.Parent = node 788 node.Children = append(node.Children, rightSiblingLeftMostChild) 789 tree.deleteChild(rightSibling, 0) 790 } 791 return 792 } 793 794 // merge with siblings 795 if rightSibling != nil { 796 // merge with right sibling 797 node.Entries = append(node.Entries, node.Parent.Entries[rightSiblingIndex-1]) 798 node.Entries = append(node.Entries, rightSibling.Entries...) 799 deletedKey = node.Parent.Entries[rightSiblingIndex-1].Key 800 tree.deleteEntry(node.Parent, rightSiblingIndex-1) 801 tree.appendChildren(node.Parent.Children[rightSiblingIndex], node) 802 tree.deleteChild(node.Parent, rightSiblingIndex) 803 } else if leftSibling != nil { 804 // merge with left sibling 805 entries := append([]*BTreeEntry(nil), leftSibling.Entries...) 806 entries = append(entries, node.Parent.Entries[leftSiblingIndex]) 807 node.Entries = append(entries, node.Entries...) 808 deletedKey = node.Parent.Entries[leftSiblingIndex].Key 809 tree.deleteEntry(node.Parent, leftSiblingIndex) 810 tree.prependChildren(node.Parent.Children[leftSiblingIndex], node) 811 tree.deleteChild(node.Parent, leftSiblingIndex) 812 } 813 814 // make the merged node the root if its parent was the root and the root is empty 815 if node.Parent == tree.root && len(tree.root.Entries) == 0 { 816 tree.root = node 817 node.Parent = nil 818 return 819 } 820 821 // parent might underflow, so try to rebalance if necessary 822 tree.rebalance(node.Parent, deletedKey) 823 } 824 825 func (tree *BTree) prependChildren(fromNode *BTreeNode, toNode *BTreeNode) { 826 children := append([]*BTreeNode(nil), fromNode.Children...) 827 toNode.Children = append(children, toNode.Children...) 828 setParent(fromNode.Children, toNode) 829 } 830 831 func (tree *BTree) appendChildren(fromNode *BTreeNode, toNode *BTreeNode) { 832 toNode.Children = append(toNode.Children, fromNode.Children...) 833 setParent(fromNode.Children, toNode) 834 } 835 836 func (tree *BTree) deleteEntry(node *BTreeNode, index int) { 837 copy(node.Entries[index:], node.Entries[index+1:]) 838 node.Entries[len(node.Entries)-1] = nil 839 node.Entries = node.Entries[:len(node.Entries)-1] 840 } 841 842 func (tree *BTree) deleteChild(node *BTreeNode, index int) { 843 if index >= len(node.Children) { 844 return 845 } 846 copy(node.Children[index:], node.Children[index+1:]) 847 node.Children[len(node.Children)-1] = nil 848 node.Children = node.Children[:len(node.Children)-1] 849 } 850 851 // MarshalJSON implements the interface MarshalJSON for json.Marshal. 852 func (tree *BTree) MarshalJSON() ([]byte, error) { 853 return json.Marshal(tree.Map()) 854 }