gtree_avltree.go 20 KB

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