github.com/zhongdalu/gf@v1.0.0/g/container/gtree/gtree_avltree.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 "encoding/json" 11 "fmt" 12 13 "github.com/zhongdalu/gf/g/container/gvar" 14 "github.com/zhongdalu/gf/g/internal/rwmutex" 15 ) 16 17 // AVLTree holds elements of the AVL tree. 18 type AVLTree struct { 19 mu *rwmutex.RWMutex 20 root *AVLTreeNode 21 comparator func(v1, v2 interface{}) int 22 size int 23 } 24 25 // AVLTreeNode is a single element within the tree. 26 type AVLTreeNode struct { 27 Key interface{} 28 Value interface{} 29 parent *AVLTreeNode 30 children [2]*AVLTreeNode 31 b int8 32 } 33 34 // NewAVLTree instantiates an AVL tree with the custom key comparator. 35 // The parameter <unsafe> used to specify whether using tree in un-concurrent-safety, 36 // which is false in default. 37 func NewAVLTree(comparator func(v1, v2 interface{}) int, unsafe ...bool) *AVLTree { 38 return &AVLTree{ 39 mu: rwmutex.New(unsafe...), 40 comparator: comparator, 41 } 42 } 43 44 // NewAVLTreeFrom instantiates an AVL tree with the custom key comparator and data map. 45 // The parameter <unsafe> used to specify whether using tree in un-concurrent-safety, 46 // which is false in default. 47 func NewAVLTreeFrom(comparator func(v1, v2 interface{}) int, data map[interface{}]interface{}, unsafe ...bool) *AVLTree { 48 tree := NewAVLTree(comparator, unsafe...) 49 for k, v := range data { 50 tree.put(k, v, nil, &tree.root) 51 } 52 return tree 53 } 54 55 // Clone returns a new tree with a copy of current tree. 56 func (tree *AVLTree) Clone(unsafe ...bool) *AVLTree { 57 newTree := NewAVLTree(tree.comparator, !tree.mu.IsSafe()) 58 newTree.Sets(tree.Map()) 59 return newTree 60 } 61 62 // Set inserts node into the tree. 63 func (tree *AVLTree) Set(key interface{}, value interface{}) { 64 tree.mu.Lock() 65 defer tree.mu.Unlock() 66 tree.put(key, value, nil, &tree.root) 67 } 68 69 // Sets batch sets key-values to the tree. 70 func (tree *AVLTree) Sets(data map[interface{}]interface{}) { 71 tree.mu.Lock() 72 defer tree.mu.Unlock() 73 for key, value := range data { 74 tree.put(key, value, nil, &tree.root) 75 } 76 } 77 78 // Search searches the tree with given <key>. 79 // Second return parameter <found> is true if key was found, otherwise false. 80 func (tree *AVLTree) Search(key interface{}) (value interface{}, found bool) { 81 tree.mu.RLock() 82 defer tree.mu.RUnlock() 83 return tree.doSearch(key) 84 } 85 86 // doSearch searches the tree with given <key>. 87 // Second return parameter <found> is true if key was found, otherwise false. 88 func (tree *AVLTree) doSearch(key interface{}) (value interface{}, found bool) { 89 n := tree.root 90 for n != nil { 91 cmp := tree.comparator(key, n.Key) 92 switch { 93 case cmp == 0: 94 return n.Value, true 95 case cmp < 0: 96 n = n.children[0] 97 case cmp > 0: 98 n = n.children[1] 99 } 100 } 101 return nil, false 102 } 103 104 // Get searches the node in the tree by <key> and returns its value or nil if key is not found in tree. 105 func (tree *AVLTree) Get(key interface{}) (value interface{}) { 106 value, _ = tree.Search(key) 107 return 108 } 109 110 // doSetWithLockCheck checks whether value of the key exists with mutex.Lock, 111 // if not exists, set value to the map with given <key>, 112 // or else just return the existing value. 113 // 114 // When setting value, if <value> is type of <func() interface {}>, 115 // it will be executed with mutex.Lock of the hash map, 116 // and its return value will be set to the map with <key>. 117 // 118 // It returns value with given <key>. 119 func (tree *AVLTree) doSetWithLockCheck(key interface{}, value interface{}) interface{} { 120 tree.mu.Lock() 121 defer tree.mu.Unlock() 122 if v, ok := tree.doSearch(key); ok { 123 return v 124 } 125 if f, ok := value.(func() interface{}); ok { 126 value = f() 127 } 128 tree.put(key, value, nil, &tree.root) 129 return value 130 } 131 132 // GetOrSet returns the value by key, 133 // or set value with given <value> if not exist and returns this value. 134 func (tree *AVLTree) GetOrSet(key interface{}, value interface{}) interface{} { 135 if v, ok := tree.Search(key); !ok { 136 return tree.doSetWithLockCheck(key, value) 137 } else { 138 return v 139 } 140 } 141 142 // GetOrSetFunc returns the value by key, 143 // or sets value with return value of callback function <f> if not exist 144 // and returns this value. 145 func (tree *AVLTree) GetOrSetFunc(key interface{}, f func() interface{}) interface{} { 146 if v, ok := tree.Search(key); !ok { 147 return tree.doSetWithLockCheck(key, f()) 148 } else { 149 return v 150 } 151 } 152 153 // GetOrSetFuncLock returns the value by key, 154 // or sets value with return value of callback function <f> if not exist 155 // and returns this value. 156 // 157 // GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function <f> 158 // with mutex.Lock of the hash map. 159 func (tree *AVLTree) GetOrSetFuncLock(key interface{}, f func() interface{}) interface{} { 160 if v, ok := tree.Search(key); !ok { 161 return tree.doSetWithLockCheck(key, f) 162 } else { 163 return v 164 } 165 } 166 167 // GetVar returns a gvar.Var with the value by given <key>. 168 // The returned gvar.Var is un-concurrent safe. 169 func (tree *AVLTree) GetVar(key interface{}) *gvar.Var { 170 return gvar.New(tree.Get(key), true) 171 } 172 173 // GetVarOrSet returns a gvar.Var with result from GetVarOrSet. 174 // The returned gvar.Var is un-concurrent safe. 175 func (tree *AVLTree) GetVarOrSet(key interface{}, value interface{}) *gvar.Var { 176 return gvar.New(tree.GetOrSet(key, value), true) 177 } 178 179 // GetVarOrSetFunc returns a gvar.Var with result from GetOrSetFunc. 180 // The returned gvar.Var is un-concurrent safe. 181 func (tree *AVLTree) GetVarOrSetFunc(key interface{}, f func() interface{}) *gvar.Var { 182 return gvar.New(tree.GetOrSetFunc(key, f), true) 183 } 184 185 // GetVarOrSetFuncLock returns a gvar.Var with result from GetOrSetFuncLock. 186 // The returned gvar.Var is un-concurrent safe. 187 func (tree *AVLTree) GetVarOrSetFuncLock(key interface{}, f func() interface{}) *gvar.Var { 188 return gvar.New(tree.GetOrSetFuncLock(key, f), true) 189 } 190 191 // SetIfNotExist sets <value> to the map if the <key> does not exist, then return true. 192 // It returns false if <key> exists, and <value> would be ignored. 193 func (tree *AVLTree) SetIfNotExist(key interface{}, value interface{}) bool { 194 if !tree.Contains(key) { 195 tree.doSetWithLockCheck(key, value) 196 return true 197 } 198 return false 199 } 200 201 // SetIfNotExistFunc sets value with return value of callback function <f>, then return true. 202 // It returns false if <key> exists, and <value> would be ignored. 203 func (tree *AVLTree) SetIfNotExistFunc(key interface{}, f func() interface{}) bool { 204 if !tree.Contains(key) { 205 tree.doSetWithLockCheck(key, f()) 206 return true 207 } 208 return false 209 } 210 211 // SetIfNotExistFuncLock sets value with return value of callback function <f>, then return true. 212 // It returns false if <key> exists, and <value> would be ignored. 213 // 214 // SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that 215 // it executes function <f> with mutex.Lock of the hash map. 216 func (tree *AVLTree) SetIfNotExistFuncLock(key interface{}, f func() interface{}) bool { 217 if !tree.Contains(key) { 218 tree.doSetWithLockCheck(key, f) 219 return true 220 } 221 return false 222 } 223 224 // Contains checks whether <key> exists in the tree. 225 func (tree *AVLTree) Contains(key interface{}) bool { 226 _, ok := tree.Search(key) 227 return ok 228 } 229 230 // Remove removes the node from the tree by key. 231 // Key should adhere to the comparator's type assertion, otherwise method panics. 232 func (tree *AVLTree) Remove(key interface{}) (value interface{}) { 233 tree.mu.Lock() 234 defer tree.mu.Unlock() 235 value, _ = tree.remove(key, &tree.root) 236 return 237 } 238 239 // Removes batch deletes values of the tree by <keys>. 240 func (tree *AVLTree) Removes(keys []interface{}) { 241 tree.mu.Lock() 242 defer tree.mu.Unlock() 243 for _, key := range keys { 244 tree.remove(key, &tree.root) 245 } 246 } 247 248 // IsEmpty returns true if tree does not contain any nodes. 249 func (tree *AVLTree) IsEmpty() bool { 250 return tree.Size() == 0 251 } 252 253 // Size returns number of nodes in the tree. 254 func (tree *AVLTree) Size() int { 255 tree.mu.RLock() 256 defer tree.mu.RUnlock() 257 return tree.size 258 } 259 260 // Keys returns all keys in asc order. 261 func (tree *AVLTree) Keys() []interface{} { 262 keys := make([]interface{}, tree.Size()) 263 index := 0 264 tree.IteratorAsc(func(key, value interface{}) bool { 265 keys[index] = key 266 index++ 267 return true 268 }) 269 return keys 270 } 271 272 // Values returns all values in asc order based on the key. 273 func (tree *AVLTree) Values() []interface{} { 274 values := make([]interface{}, tree.Size()) 275 index := 0 276 tree.IteratorAsc(func(key, value interface{}) bool { 277 values[index] = value 278 index++ 279 return true 280 }) 281 return values 282 } 283 284 // Left returns the minimum element of the AVL tree 285 // or nil if the tree is empty. 286 func (tree *AVLTree) Left() *AVLTreeNode { 287 tree.mu.RLock() 288 defer tree.mu.RUnlock() 289 node := tree.bottom(0) 290 if tree.mu.IsSafe() { 291 return &AVLTreeNode{ 292 Key: node.Key, 293 Value: node.Value, 294 } 295 } 296 return node 297 } 298 299 // Right returns the maximum element of the AVL tree 300 // or nil if the tree is empty. 301 func (tree *AVLTree) Right() *AVLTreeNode { 302 tree.mu.RLock() 303 defer tree.mu.RUnlock() 304 node := tree.bottom(1) 305 if tree.mu.IsSafe() { 306 return &AVLTreeNode{ 307 Key: node.Key, 308 Value: node.Value, 309 } 310 } 311 return node 312 } 313 314 // Floor Finds floor node of the input key, return the floor node or nil if no floor node is found. 315 // Second return parameter is true if floor was found, otherwise false. 316 // 317 // Floor node is defined as the largest node that is smaller than or equal to the given node. 318 // A floor node may not be found, either because the tree is empty, or because 319 // all nodes in the tree is larger than the given node. 320 // 321 // Key should adhere to the comparator's type assertion, otherwise method panics. 322 func (tree *AVLTree) Floor(key interface{}) (floor *AVLTreeNode, found bool) { 323 tree.mu.RLock() 324 defer tree.mu.RUnlock() 325 n := tree.root 326 for n != nil { 327 c := tree.comparator(key, n.Key) 328 switch { 329 case c == 0: 330 return n, true 331 case c < 0: 332 n = n.children[0] 333 case c > 0: 334 floor, found = n, true 335 n = n.children[1] 336 } 337 } 338 if found { 339 return 340 } 341 return nil, false 342 } 343 344 // Ceiling finds ceiling node of the input key, return the ceiling node or nil if no ceiling node is found. 345 // Second return parameter is true if ceiling was found, otherwise false. 346 // 347 // Ceiling node is defined as the smallest node that is larger than or equal to the given node. 348 // A ceiling node may not be found, either because the tree is empty, or because 349 // all nodes in the tree is smaller than the given node. 350 // 351 // Key should adhere to the comparator's type assertion, otherwise method panics. 352 func (tree *AVLTree) Ceiling(key interface{}) (ceiling *AVLTreeNode, found bool) { 353 tree.mu.RLock() 354 defer tree.mu.RUnlock() 355 n := tree.root 356 for n != nil { 357 c := tree.comparator(key, n.Key) 358 switch { 359 case c == 0: 360 return n, true 361 case c > 0: 362 n = n.children[1] 363 case c < 0: 364 ceiling, found = n, true 365 n = n.children[0] 366 } 367 } 368 if found { 369 return 370 } 371 return nil, false 372 } 373 374 // Clear removes all nodes from the tree. 375 func (tree *AVLTree) Clear() { 376 tree.mu.Lock() 377 defer tree.mu.Unlock() 378 tree.root = nil 379 tree.size = 0 380 } 381 382 // String returns a string representation of container 383 func (tree *AVLTree) String() string { 384 tree.mu.RLock() 385 defer tree.mu.RUnlock() 386 str := "AVLTree\n" 387 if tree.size != 0 { 388 output(tree.root, "", true, &str) 389 } 390 return str 391 } 392 393 // Print prints the tree to stdout. 394 func (tree *AVLTree) Print() { 395 fmt.Println(tree.String()) 396 } 397 398 // Map returns all key-value items as map. 399 func (tree *AVLTree) Map() map[interface{}]interface{} { 400 m := make(map[interface{}]interface{}, tree.Size()) 401 tree.IteratorAsc(func(key, value interface{}) bool { 402 m[key] = value 403 return true 404 }) 405 return m 406 } 407 408 // Flip exchanges key-value of the tree to value-key. 409 // Note that you should guarantee the value is the same type as key, 410 // or else the comparator would panic. 411 // 412 // If the type of value is different with key, you pass the new <comparator>. 413 func (tree *AVLTree) Flip(comparator ...func(v1, v2 interface{}) int) { 414 t := (*AVLTree)(nil) 415 if len(comparator) > 0 { 416 t = NewAVLTree(comparator[0], !tree.mu.IsSafe()) 417 } else { 418 t = NewAVLTree(tree.comparator, !tree.mu.IsSafe()) 419 } 420 tree.IteratorAsc(func(key, value interface{}) bool { 421 t.put(value, key, nil, &t.root) 422 return true 423 }) 424 tree.mu.Lock() 425 tree.root = t.root 426 tree.size = t.size 427 tree.mu.Unlock() 428 } 429 430 // Iterator is alias of IteratorAsc. 431 func (tree *AVLTree) Iterator(f func(key, value interface{}) bool) { 432 tree.IteratorAsc(f) 433 } 434 435 // IteratorAsc iterates the tree in ascending order with given callback function <f>. 436 // If <f> returns true, then it continues iterating; or false to stop. 437 func (tree *AVLTree) IteratorAsc(f func(key, value interface{}) bool) { 438 tree.mu.RLock() 439 defer tree.mu.RUnlock() 440 node := tree.bottom(0) 441 for node != nil { 442 if !f(node.Key, node.Value) { 443 return 444 } 445 node = node.Next() 446 } 447 } 448 449 // IteratorDesc iterates the tree in descending order with given callback function <f>. 450 // If <f> returns true, then it continues iterating; or false to stop. 451 func (tree *AVLTree) IteratorDesc(f func(key, value interface{}) bool) { 452 tree.mu.RLock() 453 defer tree.mu.RUnlock() 454 node := tree.bottom(1) 455 for node != nil { 456 if !f(node.Key, node.Value) { 457 return 458 } 459 node = node.Prev() 460 } 461 } 462 463 func (tree *AVLTree) put(key interface{}, value interface{}, p *AVLTreeNode, qp **AVLTreeNode) bool { 464 q := *qp 465 if q == nil { 466 tree.size++ 467 *qp = &AVLTreeNode{Key: key, Value: value, parent: p} 468 return true 469 } 470 471 c := tree.comparator(key, q.Key) 472 if c == 0 { 473 q.Key = key 474 q.Value = value 475 return false 476 } 477 478 if c < 0 { 479 c = -1 480 } else { 481 c = 1 482 } 483 a := (c + 1) / 2 484 if tree.put(key, value, q, &q.children[a]) { 485 return putFix(int8(c), qp) 486 } 487 return false 488 } 489 490 func (tree *AVLTree) remove(key interface{}, qp **AVLTreeNode) (value interface{}, fix bool) { 491 q := *qp 492 if q == nil { 493 return nil, false 494 } 495 496 c := tree.comparator(key, q.Key) 497 if c == 0 { 498 tree.size-- 499 value = q.Value 500 fix = true 501 if q.children[1] == nil { 502 if q.children[0] != nil { 503 q.children[0].parent = q.parent 504 } 505 *qp = q.children[0] 506 return 507 } 508 if removeMin(&q.children[1], &q.Key, &q.Value) { 509 return value, removeFix(-1, qp) 510 } 511 return 512 } 513 514 if c < 0 { 515 c = -1 516 } else { 517 c = 1 518 } 519 a := (c + 1) / 2 520 value, fix = tree.remove(key, &q.children[a]) 521 if fix { 522 return value, removeFix(int8(-c), qp) 523 } 524 return value, false 525 } 526 527 func removeMin(qp **AVLTreeNode, minKey *interface{}, minVal *interface{}) bool { 528 q := *qp 529 if q.children[0] == nil { 530 *minKey = q.Key 531 *minVal = q.Value 532 if q.children[1] != nil { 533 q.children[1].parent = q.parent 534 } 535 *qp = q.children[1] 536 return true 537 } 538 fix := removeMin(&q.children[0], minKey, minVal) 539 if fix { 540 return removeFix(1, qp) 541 } 542 return false 543 } 544 545 func putFix(c int8, t **AVLTreeNode) bool { 546 s := *t 547 if s.b == 0 { 548 s.b = c 549 return true 550 } 551 552 if s.b == -c { 553 s.b = 0 554 return false 555 } 556 557 if s.children[(c+1)/2].b == c { 558 s = singleRotate(c, s) 559 } else { 560 s = doubleRotate(c, s) 561 } 562 *t = s 563 return false 564 } 565 566 func removeFix(c int8, t **AVLTreeNode) bool { 567 s := *t 568 if s.b == 0 { 569 s.b = c 570 return false 571 } 572 573 if s.b == -c { 574 s.b = 0 575 return true 576 } 577 578 a := (c + 1) / 2 579 if s.children[a].b == 0 { 580 s = rotate(c, s) 581 s.b = -c 582 *t = s 583 return false 584 } 585 586 if s.children[a].b == c { 587 s = singleRotate(c, s) 588 } else { 589 s = doubleRotate(c, s) 590 } 591 *t = s 592 return true 593 } 594 595 func singleRotate(c int8, s *AVLTreeNode) *AVLTreeNode { 596 s.b = 0 597 s = rotate(c, s) 598 s.b = 0 599 return s 600 } 601 602 func doubleRotate(c int8, s *AVLTreeNode) *AVLTreeNode { 603 a := (c + 1) / 2 604 r := s.children[a] 605 s.children[a] = rotate(-c, s.children[a]) 606 p := rotate(c, s) 607 608 switch { 609 default: 610 s.b = 0 611 r.b = 0 612 case p.b == c: 613 s.b = -c 614 r.b = 0 615 case p.b == -c: 616 s.b = 0 617 r.b = c 618 } 619 620 p.b = 0 621 return p 622 } 623 624 func rotate(c int8, s *AVLTreeNode) *AVLTreeNode { 625 a := (c + 1) / 2 626 r := s.children[a] 627 s.children[a] = r.children[a^1] 628 if s.children[a] != nil { 629 s.children[a].parent = s 630 } 631 r.children[a^1] = s 632 r.parent = s.parent 633 s.parent = r 634 return r 635 } 636 637 func (tree *AVLTree) bottom(d int) *AVLTreeNode { 638 n := tree.root 639 if n == nil { 640 return nil 641 } 642 643 for c := n.children[d]; c != nil; c = n.children[d] { 644 n = c 645 } 646 return n 647 } 648 649 // Prev returns the previous element in an inorder 650 // walk of the AVL tree. 651 func (node *AVLTreeNode) Prev() *AVLTreeNode { 652 return node.walk1(0) 653 } 654 655 // Next returns the next element in an inorder 656 // walk of the AVL tree. 657 func (node *AVLTreeNode) Next() *AVLTreeNode { 658 return node.walk1(1) 659 } 660 661 func (node *AVLTreeNode) walk1(a int) *AVLTreeNode { 662 if node == nil { 663 return nil 664 } 665 n := node 666 if n.children[a] != nil { 667 n = n.children[a] 668 for n.children[a^1] != nil { 669 n = n.children[a^1] 670 } 671 return n 672 } 673 674 p := n.parent 675 for p != nil && p.children[a] == n { 676 n = p 677 p = p.parent 678 } 679 return p 680 } 681 682 func output(node *AVLTreeNode, prefix string, isTail bool, str *string) { 683 if node.children[1] != nil { 684 newPrefix := prefix 685 if isTail { 686 newPrefix += "│ " 687 } else { 688 newPrefix += " " 689 } 690 output(node.children[1], newPrefix, false, str) 691 } 692 *str += prefix 693 if isTail { 694 *str += "└── " 695 } else { 696 *str += "┌── " 697 } 698 *str += fmt.Sprintf("%v\n", node.Key) 699 if node.children[0] != nil { 700 newPrefix := prefix 701 if isTail { 702 newPrefix += " " 703 } else { 704 newPrefix += "│ " 705 } 706 output(node.children[0], newPrefix, true, str) 707 } 708 } 709 710 // MarshalJSON implements the interface MarshalJSON for json.Marshal. 711 func (tree *AVLTree) MarshalJSON() ([]byte, error) { 712 return json.Marshal(tree.Map()) 713 }