github.com/wangyougui/gf/v2@v2.6.5/container/gtree/gtree_avltree.go (about)

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