gtree_avltree.go 20 KB

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