gitee.com/quant1x/gox@v1.21.2/util/avltree/avltree.go (about)

     1  // Copyright (c) 2017, Benjamin Scher Purcell. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package avltree implements an AVL balanced binary tree.
     6  //
     7  // Structure is not thread safe.
     8  //
     9  // References: https://en.wikipedia.org/wiki/AVL_tree
    10  package avltree
    11  
    12  import (
    13  	"fmt"
    14  	"gitee.com/quant1x/gox/util/internal"
    15  )
    16  
    17  func assertTreeImplementation() {
    18  	var _ internal.Tree = new(Tree)
    19  }
    20  
    21  // Tree holds elements of the AVL tree.
    22  type Tree struct {
    23  	Root       *Node               // Root node
    24  	Comparator internal.Comparator // Key comparator
    25  	size       int                 // Total number of keys in the tree
    26  }
    27  
    28  // Node is a single element within the tree
    29  type Node struct {
    30  	Key      interface{}
    31  	Value    interface{}
    32  	Parent   *Node    // Parent node
    33  	Children [2]*Node // Children nodes
    34  	b        int8
    35  }
    36  
    37  // NewWith instantiates an AVL tree with the custom comparator.
    38  func NewWith(comparator internal.Comparator) *Tree {
    39  	return &Tree{Comparator: comparator}
    40  }
    41  
    42  // NewWithIntComparator instantiates an AVL tree with the IntComparator, i.e. keys are of type int.
    43  func NewWithIntComparator() *Tree {
    44  	return &Tree{Comparator: internal.IntComparator}
    45  }
    46  
    47  // NewWithStringComparator instantiates an AVL tree with the StringComparator, i.e. keys are of type string.
    48  func NewWithStringComparator() *Tree {
    49  	return &Tree{Comparator: internal.StringComparator}
    50  }
    51  
    52  // Put inserts node into the tree.
    53  // Key should adhere to the comparator's type assertion, otherwise method panics.
    54  func (t *Tree) Put(key interface{}, value interface{}) {
    55  	t.put(key, value, nil, &t.Root)
    56  }
    57  
    58  // Get searches the node in the tree by key and returns its value or nil if key is not found in tree.
    59  // Second return parameter is true if key was found, otherwise false.
    60  // Key should adhere to the comparator's type assertion, otherwise method panics.
    61  func (t *Tree) Get(key interface{}) (value interface{}, found bool) {
    62  	n := t.Root
    63  	for n != nil {
    64  		cmp := t.Comparator(key, n.Key)
    65  		switch {
    66  		case cmp == 0:
    67  			return n.Value, true
    68  		case cmp < 0:
    69  			n = n.Children[0]
    70  		case cmp > 0:
    71  			n = n.Children[1]
    72  		}
    73  	}
    74  	return nil, false
    75  }
    76  
    77  // Remove remove the node from the tree by key.
    78  // Key should adhere to the comparator's type assertion, otherwise method panics.
    79  func (t *Tree) Remove(key interface{}) {
    80  	t.remove(key, &t.Root)
    81  }
    82  
    83  // Empty returns true if tree does not contain any nodes.
    84  func (t *Tree) Empty() bool {
    85  	return t.size == 0
    86  }
    87  
    88  // Size returns the number of elements stored in the tree.
    89  func (t *Tree) Size() int {
    90  	return t.size
    91  }
    92  
    93  // Keys returns all keys in-order
    94  func (t *Tree) Keys() []interface{} {
    95  	keys := make([]interface{}, t.size)
    96  	it := t.Iterator()
    97  	for i := 0; it.Next(); i++ {
    98  		keys[i] = it.Key()
    99  	}
   100  	return keys
   101  }
   102  
   103  // Values returns all values in-order based on the key.
   104  func (t *Tree) Values() []interface{} {
   105  	values := make([]interface{}, t.size)
   106  	it := t.Iterator()
   107  	for i := 0; it.Next(); i++ {
   108  		values[i] = it.Value()
   109  	}
   110  	return values
   111  }
   112  
   113  // Left returns the minimum element of the AVL tree
   114  // or nil if the tree is empty.
   115  func (t *Tree) Left() *Node {
   116  	return t.bottom(0)
   117  }
   118  
   119  // Right returns the maximum element of the AVL tree
   120  // or nil if the tree is empty.
   121  func (t *Tree) Right() *Node {
   122  	return t.bottom(1)
   123  }
   124  
   125  // Floor Finds floor node of the input key, return the floor node or nil if no ceiling is found.
   126  // Second return parameter is true if floor was found, otherwise false.
   127  //
   128  // Floor node is defined as the largest node that is smaller than or equal to the given node.
   129  // A floor node may not be found, either because the tree is empty, or because
   130  // all nodes in the tree is larger than the given node.
   131  //
   132  // Key should adhere to the comparator's type assertion, otherwise method panics.
   133  func (t *Tree) Floor(key interface{}) (floor *Node, found bool) {
   134  	found = false
   135  	n := t.Root
   136  	for n != nil {
   137  		c := t.Comparator(key, n.Key)
   138  		switch {
   139  		case c == 0:
   140  			return n, true
   141  		case c < 0:
   142  			n = n.Children[0]
   143  		case c > 0:
   144  			floor, found = n, true
   145  			n = n.Children[1]
   146  		}
   147  	}
   148  	if found {
   149  		return
   150  	}
   151  	return nil, false
   152  }
   153  
   154  // Ceiling finds ceiling node of the input key, return the ceiling node or nil if no ceiling is found.
   155  // Second return parameter is true if ceiling was found, otherwise false.
   156  //
   157  // Ceiling node is defined as the smallest node that is larger than or equal to the given node.
   158  // A ceiling node may not be found, either because the tree is empty, or because
   159  // all nodes in the tree is smaller than the given node.
   160  //
   161  // Key should adhere to the comparator's type assertion, otherwise method panics.
   162  func (t *Tree) Ceiling(key interface{}) (floor *Node, found bool) {
   163  	found = false
   164  	n := t.Root
   165  	for n != nil {
   166  		c := t.Comparator(key, n.Key)
   167  		switch {
   168  		case c == 0:
   169  			return n, true
   170  		case c < 0:
   171  			floor, found = n, true
   172  			n = n.Children[0]
   173  		case c > 0:
   174  			n = n.Children[1]
   175  		}
   176  	}
   177  	if found {
   178  		return
   179  	}
   180  	return nil, false
   181  }
   182  
   183  // Clear removes all nodes from the tree.
   184  func (t *Tree) Clear() {
   185  	t.Root = nil
   186  	t.size = 0
   187  }
   188  
   189  // String returns a string representation of container
   190  func (t *Tree) String() string {
   191  	str := "AVLTree\n"
   192  	if !t.Empty() {
   193  		output(t.Root, "", true, &str)
   194  	}
   195  	return str
   196  }
   197  
   198  func (n *Node) String() string {
   199  	return fmt.Sprintf("%v", n.Key)
   200  }
   201  
   202  func (t *Tree) put(key interface{}, value interface{}, p *Node, qp **Node) bool {
   203  	q := *qp
   204  	if q == nil {
   205  		t.size++
   206  		*qp = &Node{Key: key, Value: value, Parent: p}
   207  		return true
   208  	}
   209  
   210  	c := t.Comparator(key, q.Key)
   211  	if c == 0 {
   212  		q.Key = key
   213  		q.Value = value
   214  		return false
   215  	}
   216  
   217  	if c < 0 {
   218  		c = -1
   219  	} else {
   220  		c = 1
   221  	}
   222  	a := (c + 1) / 2
   223  	var fix bool
   224  	fix = t.put(key, value, q, &q.Children[a])
   225  	if fix {
   226  		return putFix(int8(c), qp)
   227  	}
   228  	return false
   229  }
   230  
   231  func (t *Tree) remove(key interface{}, qp **Node) bool {
   232  	q := *qp
   233  	if q == nil {
   234  		return false
   235  	}
   236  
   237  	c := t.Comparator(key, q.Key)
   238  	if c == 0 {
   239  		t.size--
   240  		if q.Children[1] == nil {
   241  			if q.Children[0] != nil {
   242  				q.Children[0].Parent = q.Parent
   243  			}
   244  			*qp = q.Children[0]
   245  			return true
   246  		}
   247  		fix := removeMin(&q.Children[1], &q.Key, &q.Value)
   248  		if fix {
   249  			return removeFix(-1, qp)
   250  		}
   251  		return false
   252  	}
   253  
   254  	if c < 0 {
   255  		c = -1
   256  	} else {
   257  		c = 1
   258  	}
   259  	a := (c + 1) / 2
   260  	fix := t.remove(key, &q.Children[a])
   261  	if fix {
   262  		return removeFix(int8(-c), qp)
   263  	}
   264  	return false
   265  }
   266  
   267  func removeMin(qp **Node, minKey *interface{}, minVal *interface{}) bool {
   268  	q := *qp
   269  	if q.Children[0] == nil {
   270  		*minKey = q.Key
   271  		*minVal = q.Value
   272  		if q.Children[1] != nil {
   273  			q.Children[1].Parent = q.Parent
   274  		}
   275  		*qp = q.Children[1]
   276  		return true
   277  	}
   278  	fix := removeMin(&q.Children[0], minKey, minVal)
   279  	if fix {
   280  		return removeFix(1, qp)
   281  	}
   282  	return false
   283  }
   284  
   285  func putFix(c int8, t **Node) bool {
   286  	s := *t
   287  	if s.b == 0 {
   288  		s.b = c
   289  		return true
   290  	}
   291  
   292  	if s.b == -c {
   293  		s.b = 0
   294  		return false
   295  	}
   296  
   297  	if s.Children[(c+1)/2].b == c {
   298  		s = singlerot(c, s)
   299  	} else {
   300  		s = doublerot(c, s)
   301  	}
   302  	*t = s
   303  	return false
   304  }
   305  
   306  func removeFix(c int8, t **Node) bool {
   307  	s := *t
   308  	if s.b == 0 {
   309  		s.b = c
   310  		return false
   311  	}
   312  
   313  	if s.b == -c {
   314  		s.b = 0
   315  		return true
   316  	}
   317  
   318  	a := (c + 1) / 2
   319  	if s.Children[a].b == 0 {
   320  		s = rotate(c, s)
   321  		s.b = -c
   322  		*t = s
   323  		return false
   324  	}
   325  
   326  	if s.Children[a].b == c {
   327  		s = singlerot(c, s)
   328  	} else {
   329  		s = doublerot(c, s)
   330  	}
   331  	*t = s
   332  	return true
   333  }
   334  
   335  func singlerot(c int8, s *Node) *Node {
   336  	s.b = 0
   337  	s = rotate(c, s)
   338  	s.b = 0
   339  	return s
   340  }
   341  
   342  func doublerot(c int8, s *Node) *Node {
   343  	a := (c + 1) / 2
   344  	r := s.Children[a]
   345  	s.Children[a] = rotate(-c, s.Children[a])
   346  	p := rotate(c, s)
   347  
   348  	switch {
   349  	default:
   350  		s.b = 0
   351  		r.b = 0
   352  	case p.b == c:
   353  		s.b = -c
   354  		r.b = 0
   355  	case p.b == -c:
   356  		s.b = 0
   357  		r.b = c
   358  	}
   359  
   360  	p.b = 0
   361  	return p
   362  }
   363  
   364  func rotate(c int8, s *Node) *Node {
   365  	a := (c + 1) / 2
   366  	r := s.Children[a]
   367  	s.Children[a] = r.Children[a^1]
   368  	if s.Children[a] != nil {
   369  		s.Children[a].Parent = s
   370  	}
   371  	r.Children[a^1] = s
   372  	r.Parent = s.Parent
   373  	s.Parent = r
   374  	return r
   375  }
   376  
   377  func (t *Tree) bottom(d int) *Node {
   378  	n := t.Root
   379  	if n == nil {
   380  		return nil
   381  	}
   382  
   383  	for c := n.Children[d]; c != nil; c = n.Children[d] {
   384  		n = c
   385  	}
   386  	return n
   387  }
   388  
   389  // Prev returns the previous element in an inorder
   390  // walk of the AVL tree.
   391  func (n *Node) Prev() *Node {
   392  	return n.walk1(0)
   393  }
   394  
   395  // Next returns the next element in an inorder
   396  // walk of the AVL tree.
   397  func (n *Node) Next() *Node {
   398  	return n.walk1(1)
   399  }
   400  
   401  func (n *Node) walk1(a int) *Node {
   402  	if n == nil {
   403  		return nil
   404  	}
   405  
   406  	if n.Children[a] != nil {
   407  		n = n.Children[a]
   408  		for n.Children[a^1] != nil {
   409  			n = n.Children[a^1]
   410  		}
   411  		return n
   412  	}
   413  
   414  	p := n.Parent
   415  	for p != nil && p.Children[a] == n {
   416  		n = p
   417  		p = p.Parent
   418  	}
   419  	return p
   420  }
   421  
   422  func output(node *Node, prefix string, isTail bool, str *string) {
   423  	if node.Children[1] != nil {
   424  		newPrefix := prefix
   425  		if isTail {
   426  			newPrefix += "│   "
   427  		} else {
   428  			newPrefix += "    "
   429  		}
   430  		output(node.Children[1], newPrefix, false, str)
   431  	}
   432  	*str += prefix
   433  	if isTail {
   434  		*str += "└── "
   435  	} else {
   436  		*str += "┌── "
   437  	}
   438  	*str += node.String() + "\n"
   439  	if node.Children[0] != nil {
   440  		newPrefix := prefix
   441  		if isTail {
   442  			newPrefix += "    "
   443  		} else {
   444  			newPrefix += "│   "
   445  		}
   446  		output(node.Children[0], newPrefix, true, str)
   447  	}
   448  }