github.com/gogf/gf@v1.16.9/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/gogf/gf.
     6  
     7  package gtree
     8  
     9  import (
    10  	"fmt"
    11  	"github.com/gogf/gf/internal/json"
    12  
    13  	"github.com/gogf/gf/util/gconv"
    14  
    15  	"github.com/gogf/gf/container/gvar"
    16  	"github.com/gogf/gf/internal/rwmutex"
    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  	tree.mu.RLock()
   403  	defer tree.mu.RUnlock()
   404  	str := ""
   405  	if tree.size != 0 {
   406  		output(tree.root, "", true, &str)
   407  	}
   408  	return str
   409  }
   410  
   411  // Print prints the tree to stdout.
   412  func (tree *AVLTree) Print() {
   413  	fmt.Println(tree.String())
   414  }
   415  
   416  // Map returns all key-value items as map.
   417  func (tree *AVLTree) Map() map[interface{}]interface{} {
   418  	m := make(map[interface{}]interface{}, tree.Size())
   419  	tree.IteratorAsc(func(key, value interface{}) bool {
   420  		m[key] = value
   421  		return true
   422  	})
   423  	return m
   424  }
   425  
   426  // MapStrAny returns all key-value items as map[string]interface{}.
   427  func (tree *AVLTree) MapStrAny() map[string]interface{} {
   428  	m := make(map[string]interface{}, tree.Size())
   429  	tree.IteratorAsc(func(key, value interface{}) bool {
   430  		m[gconv.String(key)] = value
   431  		return true
   432  	})
   433  	return m
   434  }
   435  
   436  // Flip exchanges key-value of the tree to value-key.
   437  // Note that you should guarantee the value is the same type as key,
   438  // or else the comparator would panic.
   439  //
   440  // If the type of value is different with key, you pass the new <comparator>.
   441  func (tree *AVLTree) Flip(comparator ...func(v1, v2 interface{}) int) {
   442  	t := (*AVLTree)(nil)
   443  	if len(comparator) > 0 {
   444  		t = NewAVLTree(comparator[0], tree.mu.IsSafe())
   445  	} else {
   446  		t = NewAVLTree(tree.comparator, tree.mu.IsSafe())
   447  	}
   448  	tree.IteratorAsc(func(key, value interface{}) bool {
   449  		t.put(value, key, nil, &t.root)
   450  		return true
   451  	})
   452  	tree.mu.Lock()
   453  	tree.root = t.root
   454  	tree.size = t.size
   455  	tree.mu.Unlock()
   456  }
   457  
   458  // Iterator is alias of IteratorAsc.
   459  func (tree *AVLTree) Iterator(f func(key, value interface{}) bool) {
   460  	tree.IteratorAsc(f)
   461  }
   462  
   463  // IteratorFrom is alias of IteratorAscFrom.
   464  func (tree *AVLTree) IteratorFrom(key interface{}, match bool, f func(key, value interface{}) bool) {
   465  	tree.IteratorAscFrom(key, match, f)
   466  }
   467  
   468  // IteratorAsc iterates the tree readonly in ascending order with given callback function <f>.
   469  // If <f> returns true, then it continues iterating; or false to stop.
   470  func (tree *AVLTree) IteratorAsc(f func(key, value interface{}) bool) {
   471  	tree.mu.RLock()
   472  	defer tree.mu.RUnlock()
   473  	tree.doIteratorAsc(tree.bottom(0), f)
   474  }
   475  
   476  // IteratorAscFrom iterates the tree readonly in ascending order with given callback function <f>.
   477  // The parameter <key> specifies the start entry for iterating. The <match> specifies whether
   478  // starting iterating if the <key> is fully matched, or else using index searching iterating.
   479  // If <f> returns true, then it continues iterating; or false to stop.
   480  func (tree *AVLTree) IteratorAscFrom(key interface{}, match bool, f func(key, value interface{}) bool) {
   481  	tree.mu.RLock()
   482  	defer tree.mu.RUnlock()
   483  	node, found := tree.doSearch(key)
   484  	if match {
   485  		if found {
   486  			tree.doIteratorAsc(node, f)
   487  		}
   488  	} else {
   489  		tree.doIteratorAsc(node, f)
   490  	}
   491  }
   492  
   493  func (tree *AVLTree) doIteratorAsc(node *AVLTreeNode, f func(key, value interface{}) bool) {
   494  	for node != nil {
   495  		if !f(node.Key, node.Value) {
   496  			return
   497  		}
   498  		node = node.Next()
   499  	}
   500  }
   501  
   502  // IteratorDesc iterates the tree readonly in descending order with given callback function <f>.
   503  // If <f> returns true, then it continues iterating; or false to stop.
   504  func (tree *AVLTree) IteratorDesc(f func(key, value interface{}) bool) {
   505  	tree.mu.RLock()
   506  	defer tree.mu.RUnlock()
   507  	tree.doIteratorDesc(tree.bottom(1), f)
   508  }
   509  
   510  // IteratorDescFrom iterates the tree readonly in descending order with given callback function <f>.
   511  // The parameter <key> specifies the start entry for iterating. The <match> specifies whether
   512  // starting iterating if the <key> is fully matched, or else using index searching iterating.
   513  // If <f> returns true, then it continues iterating; or false to stop.
   514  func (tree *AVLTree) IteratorDescFrom(key interface{}, match bool, f func(key, value interface{}) bool) {
   515  	tree.mu.RLock()
   516  	defer tree.mu.RUnlock()
   517  	node, found := tree.doSearch(key)
   518  	if match {
   519  		if found {
   520  			tree.doIteratorDesc(node, f)
   521  		}
   522  	} else {
   523  		tree.doIteratorDesc(node, f)
   524  	}
   525  }
   526  
   527  func (tree *AVLTree) doIteratorDesc(node *AVLTreeNode, f func(key, value interface{}) bool) {
   528  	for node != nil {
   529  		if !f(node.Key, node.Value) {
   530  			return
   531  		}
   532  		node = node.Prev()
   533  	}
   534  }
   535  
   536  func (tree *AVLTree) put(key interface{}, value interface{}, p *AVLTreeNode, qp **AVLTreeNode) bool {
   537  	q := *qp
   538  	if q == nil {
   539  		tree.size++
   540  		*qp = &AVLTreeNode{Key: key, Value: value, parent: p}
   541  		return true
   542  	}
   543  
   544  	c := tree.getComparator()(key, q.Key)
   545  	if c == 0 {
   546  		q.Key = key
   547  		q.Value = value
   548  		return false
   549  	}
   550  
   551  	if c < 0 {
   552  		c = -1
   553  	} else {
   554  		c = 1
   555  	}
   556  	a := (c + 1) / 2
   557  	if tree.put(key, value, q, &q.children[a]) {
   558  		return putFix(int8(c), qp)
   559  	}
   560  	return false
   561  }
   562  
   563  func (tree *AVLTree) remove(key interface{}, qp **AVLTreeNode) (value interface{}, fix bool) {
   564  	q := *qp
   565  	if q == nil {
   566  		return nil, false
   567  	}
   568  
   569  	c := tree.getComparator()(key, q.Key)
   570  	if c == 0 {
   571  		tree.size--
   572  		value = q.Value
   573  		fix = true
   574  		if q.children[1] == nil {
   575  			if q.children[0] != nil {
   576  				q.children[0].parent = q.parent
   577  			}
   578  			*qp = q.children[0]
   579  			return
   580  		}
   581  		if removeMin(&q.children[1], &q.Key, &q.Value) {
   582  			return value, removeFix(-1, qp)
   583  		}
   584  		return
   585  	}
   586  
   587  	if c < 0 {
   588  		c = -1
   589  	} else {
   590  		c = 1
   591  	}
   592  	a := (c + 1) / 2
   593  	value, fix = tree.remove(key, &q.children[a])
   594  	if fix {
   595  		return value, removeFix(int8(-c), qp)
   596  	}
   597  	return value, false
   598  }
   599  
   600  func removeMin(qp **AVLTreeNode, minKey *interface{}, minVal *interface{}) bool {
   601  	q := *qp
   602  	if q.children[0] == nil {
   603  		*minKey = q.Key
   604  		*minVal = q.Value
   605  		if q.children[1] != nil {
   606  			q.children[1].parent = q.parent
   607  		}
   608  		*qp = q.children[1]
   609  		return true
   610  	}
   611  	fix := removeMin(&q.children[0], minKey, minVal)
   612  	if fix {
   613  		return removeFix(1, qp)
   614  	}
   615  	return false
   616  }
   617  
   618  func putFix(c int8, t **AVLTreeNode) bool {
   619  	s := *t
   620  	if s.b == 0 {
   621  		s.b = c
   622  		return true
   623  	}
   624  
   625  	if s.b == -c {
   626  		s.b = 0
   627  		return false
   628  	}
   629  
   630  	if s.children[(c+1)/2].b == c {
   631  		s = singleRotate(c, s)
   632  	} else {
   633  		s = doubleRotate(c, s)
   634  	}
   635  	*t = s
   636  	return false
   637  }
   638  
   639  func removeFix(c int8, t **AVLTreeNode) bool {
   640  	s := *t
   641  	if s.b == 0 {
   642  		s.b = c
   643  		return false
   644  	}
   645  
   646  	if s.b == -c {
   647  		s.b = 0
   648  		return true
   649  	}
   650  
   651  	a := (c + 1) / 2
   652  	if s.children[a].b == 0 {
   653  		s = rotate(c, s)
   654  		s.b = -c
   655  		*t = s
   656  		return false
   657  	}
   658  
   659  	if s.children[a].b == c {
   660  		s = singleRotate(c, s)
   661  	} else {
   662  		s = doubleRotate(c, s)
   663  	}
   664  	*t = s
   665  	return true
   666  }
   667  
   668  func singleRotate(c int8, s *AVLTreeNode) *AVLTreeNode {
   669  	s.b = 0
   670  	s = rotate(c, s)
   671  	s.b = 0
   672  	return s
   673  }
   674  
   675  func doubleRotate(c int8, s *AVLTreeNode) *AVLTreeNode {
   676  	a := (c + 1) / 2
   677  	r := s.children[a]
   678  	s.children[a] = rotate(-c, s.children[a])
   679  	p := rotate(c, s)
   680  
   681  	switch {
   682  	default:
   683  		s.b = 0
   684  		r.b = 0
   685  	case p.b == c:
   686  		s.b = -c
   687  		r.b = 0
   688  	case p.b == -c:
   689  		s.b = 0
   690  		r.b = c
   691  	}
   692  
   693  	p.b = 0
   694  	return p
   695  }
   696  
   697  func rotate(c int8, s *AVLTreeNode) *AVLTreeNode {
   698  	a := (c + 1) / 2
   699  	r := s.children[a]
   700  	s.children[a] = r.children[a^1]
   701  	if s.children[a] != nil {
   702  		s.children[a].parent = s
   703  	}
   704  	r.children[a^1] = s
   705  	r.parent = s.parent
   706  	s.parent = r
   707  	return r
   708  }
   709  
   710  func (tree *AVLTree) bottom(d int) *AVLTreeNode {
   711  	n := tree.root
   712  	if n == nil {
   713  		return nil
   714  	}
   715  
   716  	for c := n.children[d]; c != nil; c = n.children[d] {
   717  		n = c
   718  	}
   719  	return n
   720  }
   721  
   722  // Prev returns the previous element in an inorder
   723  // walk of the AVL tree.
   724  func (node *AVLTreeNode) Prev() *AVLTreeNode {
   725  	return node.walk1(0)
   726  }
   727  
   728  // Next returns the next element in an inorder
   729  // walk of the AVL tree.
   730  func (node *AVLTreeNode) Next() *AVLTreeNode {
   731  	return node.walk1(1)
   732  }
   733  
   734  func (node *AVLTreeNode) walk1(a int) *AVLTreeNode {
   735  	if node == nil {
   736  		return nil
   737  	}
   738  	n := node
   739  	if n.children[a] != nil {
   740  		n = n.children[a]
   741  		for n.children[a^1] != nil {
   742  			n = n.children[a^1]
   743  		}
   744  		return n
   745  	}
   746  
   747  	p := n.parent
   748  	for p != nil && p.children[a] == n {
   749  		n = p
   750  		p = p.parent
   751  	}
   752  	return p
   753  }
   754  
   755  func output(node *AVLTreeNode, prefix string, isTail bool, str *string) {
   756  	if node.children[1] != nil {
   757  		newPrefix := prefix
   758  		if isTail {
   759  			newPrefix += "│   "
   760  		} else {
   761  			newPrefix += "    "
   762  		}
   763  		output(node.children[1], newPrefix, false, str)
   764  	}
   765  	*str += prefix
   766  	if isTail {
   767  		*str += "└── "
   768  	} else {
   769  		*str += "┌── "
   770  	}
   771  	*str += fmt.Sprintf("%v\n", node.Key)
   772  	if node.children[0] != nil {
   773  		newPrefix := prefix
   774  		if isTail {
   775  			newPrefix += "    "
   776  		} else {
   777  			newPrefix += "│   "
   778  		}
   779  		output(node.children[0], newPrefix, true, str)
   780  	}
   781  }
   782  
   783  // MarshalJSON implements the interface MarshalJSON for json.Marshal.
   784  func (tree *AVLTree) MarshalJSON() ([]byte, error) {
   785  	return json.Marshal(tree.Map())
   786  }
   787  
   788  // getComparator returns the comparator if it's previously set,
   789  // or else it panics.
   790  func (tree *AVLTree) getComparator() func(a, b interface{}) int {
   791  	if tree.comparator == nil {
   792  		panic("comparator is missing for tree")
   793  	}
   794  	return tree.comparator
   795  }