github.com/biogo/store@v0.0.0-20201120204734-aad293a2328f/llrb/llrb.go (about)

     1  // Copyright ©2012 The bíogo Authors. 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 llrb implements Left-Leaning Red Black trees as described by Robert Sedgewick.
     6  //
     7  // More details relating to the implementation are available at the following locations:
     8  //
     9  //  http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf
    10  //  http://www.cs.princeton.edu/~rs/talks/LLRB/Java/RedBlackBST.java
    11  //  http://www.teachsolaisgames.com/articles/balanced_left_leaning.html
    12  package llrb
    13  
    14  const (
    15  	TD234 = iota
    16  	BU23
    17  )
    18  
    19  // Operation mode of the LLRB tree.
    20  const Mode = BU23
    21  
    22  func init() {
    23  	if Mode != TD234 && Mode != BU23 {
    24  		panic("llrb: unknown mode")
    25  	}
    26  }
    27  
    28  // A Comparable is a type that can be inserted into a Tree or used as a range
    29  // or equality query on the tree,
    30  type Comparable interface {
    31  	// Compare returns a value indicating the sort order relationship between the
    32  	// receiver and the parameter.
    33  	//
    34  	// Given c = a.Compare(b):
    35  	//  c < 0 if a < b;
    36  	//  c == 0 if a == b; and
    37  	//  c > 0 if a > b.
    38  	//
    39  	Compare(Comparable) int
    40  }
    41  
    42  // A Color represents the color of a Node.
    43  type Color bool
    44  
    45  // String returns a string representation of a Color.
    46  func (c Color) String() string {
    47  	if c {
    48  		return "Black"
    49  	}
    50  	return "Red"
    51  }
    52  
    53  const (
    54  	// Red as false give us the defined behaviour that new nodes are red. Although this
    55  	// is incorrect for the root node, that is resolved on the first insertion.
    56  	Red   Color = false
    57  	Black Color = true
    58  )
    59  
    60  // A Node represents a node in the LLRB tree.
    61  type Node struct {
    62  	Elem        Comparable
    63  	Left, Right *Node
    64  	Color       Color
    65  }
    66  
    67  // A Tree manages the root node of an LLRB tree. Public methods are exposed through this type.
    68  type Tree struct {
    69  	Root  *Node // Root node of the tree.
    70  	Count int   // Number of elements stored.
    71  }
    72  
    73  // Helper methods
    74  
    75  // color returns the effect color of a Node. A nil node returns black.
    76  func (n *Node) color() Color {
    77  	if n == nil {
    78  		return Black
    79  	}
    80  	return n.Color
    81  }
    82  
    83  // (a,c)b -rotL-> ((a,)b,)c
    84  func (n *Node) rotateLeft() (root *Node) {
    85  	// Assumes: n has two children.
    86  	root = n.Right
    87  	n.Right = root.Left
    88  	root.Left = n
    89  	root.Color = n.Color
    90  	n.Color = Red
    91  	return
    92  }
    93  
    94  // (a,c)b -rotR-> (,(,c)b)a
    95  func (n *Node) rotateRight() (root *Node) {
    96  	// Assumes: n has two children.
    97  	root = n.Left
    98  	n.Left = root.Right
    99  	root.Right = n
   100  	root.Color = n.Color
   101  	n.Color = Red
   102  	return
   103  }
   104  
   105  // (aR,cR)bB -flipC-> (aB,cB)bR | (aB,cB)bR -flipC-> (aR,cR)bB
   106  func (n *Node) flipColors() {
   107  	// Assumes: n has two children.
   108  	n.Color = !n.Color
   109  	n.Left.Color = !n.Left.Color
   110  	n.Right.Color = !n.Right.Color
   111  }
   112  
   113  // fixUp ensures that black link balance is correct, that red nodes lean left,
   114  // and that 4 nodes are split in the case of BU23 and properly balanced in TD234.
   115  func (n *Node) fixUp() *Node {
   116  	if n.Right.color() == Red {
   117  		if Mode == TD234 && n.Right.Left.color() == Red {
   118  			n.Right = n.Right.rotateRight()
   119  		}
   120  		n = n.rotateLeft()
   121  	}
   122  	if n.Left.color() == Red && n.Left.Left.color() == Red {
   123  		n = n.rotateRight()
   124  	}
   125  	if Mode == BU23 && n.Left.color() == Red && n.Right.color() == Red {
   126  		n.flipColors()
   127  	}
   128  	return n
   129  }
   130  
   131  func (n *Node) moveRedLeft() *Node {
   132  	n.flipColors()
   133  	if n.Right.Left.color() == Red {
   134  		n.Right = n.Right.rotateRight()
   135  		n = n.rotateLeft()
   136  		n.flipColors()
   137  		if Mode == TD234 && n.Right.Right.color() == Red {
   138  			n.Right = n.Right.rotateLeft()
   139  		}
   140  	}
   141  	return n
   142  }
   143  
   144  func (n *Node) moveRedRight() *Node {
   145  	n.flipColors()
   146  	if n.Left.Left.color() == Red {
   147  		n = n.rotateRight()
   148  		n.flipColors()
   149  	}
   150  	return n
   151  }
   152  
   153  // Len returns the number of elements stored in the Tree.
   154  func (t *Tree) Len() int {
   155  	return t.Count
   156  }
   157  
   158  // Get returns the first match of q in the Tree. If insertion without
   159  // replacement is used, this is probably not what you want.
   160  func (t *Tree) Get(q Comparable) Comparable {
   161  	if t.Root == nil {
   162  		return nil
   163  	}
   164  	n := t.Root.search(q)
   165  	if n == nil {
   166  		return nil
   167  	}
   168  	return n.Elem
   169  }
   170  
   171  func (n *Node) search(q Comparable) *Node {
   172  	for n != nil {
   173  		switch c := q.Compare(n.Elem); {
   174  		case c == 0:
   175  			return n
   176  		case c < 0:
   177  			n = n.Left
   178  		default:
   179  			n = n.Right
   180  		}
   181  	}
   182  
   183  	return n
   184  }
   185  
   186  // Insert inserts the Comparable e into the Tree at the first match found
   187  // with e or when a nil node is reached. Insertion without replacement can
   188  // specified by ensuring that e.Compare() never returns 0. If insert without
   189  // replacement is performed, a distinct query Comparable must be used that
   190  // can return 0 with a Compare() call.
   191  func (t *Tree) Insert(e Comparable) {
   192  	var d int
   193  	t.Root, d = t.Root.insert(e)
   194  	t.Count += d
   195  	t.Root.Color = Black
   196  }
   197  
   198  func (n *Node) insert(e Comparable) (root *Node, d int) {
   199  	if n == nil {
   200  		return &Node{Elem: e}, 1
   201  	} else if n.Elem == nil {
   202  		n.Elem = e
   203  		return n, 1
   204  	}
   205  
   206  	if Mode == TD234 {
   207  		if n.Left.color() == Red && n.Right.color() == Red {
   208  			n.flipColors()
   209  		}
   210  	}
   211  
   212  	switch c := e.Compare(n.Elem); {
   213  	case c == 0:
   214  		n.Elem = e
   215  	case c < 0:
   216  		n.Left, d = n.Left.insert(e)
   217  	default:
   218  		n.Right, d = n.Right.insert(e)
   219  	}
   220  
   221  	if n.Right.color() == Red && n.Left.color() == Black {
   222  		n = n.rotateLeft()
   223  	}
   224  	if n.Left.color() == Red && n.Left.Left.color() == Red {
   225  		n = n.rotateRight()
   226  	}
   227  
   228  	if Mode == BU23 {
   229  		if n.Left.color() == Red && n.Right.color() == Red {
   230  			n.flipColors()
   231  		}
   232  	}
   233  
   234  	root = n
   235  
   236  	return
   237  }
   238  
   239  // DeleteMin deletes the node with the minimum value in the tree. If insertion without
   240  // replacement has been used, the left-most minimum will be deleted.
   241  func (t *Tree) DeleteMin() {
   242  	if t.Root == nil {
   243  		return
   244  	}
   245  	var d int
   246  	t.Root, d = t.Root.deleteMin()
   247  	t.Count += d
   248  	if t.Root == nil {
   249  		return
   250  	}
   251  	t.Root.Color = Black
   252  }
   253  
   254  func (n *Node) deleteMin() (root *Node, d int) {
   255  	if n.Left == nil {
   256  		return nil, -1
   257  	}
   258  	if n.Left.color() == Black && n.Left.Left.color() == Black {
   259  		n = n.moveRedLeft()
   260  	}
   261  	n.Left, d = n.Left.deleteMin()
   262  
   263  	root = n.fixUp()
   264  
   265  	return
   266  }
   267  
   268  // DeleteMax deletes the node with the maximum value in the tree. If insertion without
   269  // replacement has been used, the right-most maximum will be deleted.
   270  func (t *Tree) DeleteMax() {
   271  	if t.Root == nil {
   272  		return
   273  	}
   274  	var d int
   275  	t.Root, d = t.Root.deleteMax()
   276  	t.Count += d
   277  	if t.Root == nil {
   278  		return
   279  	}
   280  	t.Root.Color = Black
   281  }
   282  
   283  func (n *Node) deleteMax() (root *Node, d int) {
   284  	if n.Left != nil && n.Left.color() == Red {
   285  		n = n.rotateRight()
   286  	}
   287  	if n.Right == nil {
   288  		return nil, -1
   289  	}
   290  	if n.Right.color() == Black && n.Right.Left.color() == Black {
   291  		n = n.moveRedRight()
   292  	}
   293  	n.Right, d = n.Right.deleteMax()
   294  
   295  	root = n.fixUp()
   296  
   297  	return
   298  }
   299  
   300  // Delete deletes the node that matches e according to Compare(). Note that Compare must
   301  // identify the target node uniquely and in cases where non-unique keys are used,
   302  // attributes used to break ties must be used to determine tree ordering during insertion.
   303  func (t *Tree) Delete(e Comparable) {
   304  	if t.Root == nil {
   305  		return
   306  	}
   307  	var d int
   308  	t.Root, d = t.Root.delete(e)
   309  	t.Count += d
   310  	if t.Root == nil {
   311  		return
   312  	}
   313  	t.Root.Color = Black
   314  }
   315  
   316  func (n *Node) delete(e Comparable) (root *Node, d int) {
   317  	if e.Compare(n.Elem) < 0 {
   318  		if n.Left != nil {
   319  			if n.Left.color() == Black && n.Left.Left.color() == Black {
   320  				n = n.moveRedLeft()
   321  			}
   322  			n.Left, d = n.Left.delete(e)
   323  		}
   324  	} else {
   325  		if n.Left.color() == Red {
   326  			n = n.rotateRight()
   327  		}
   328  		if n.Right == nil && e.Compare(n.Elem) == 0 {
   329  			return nil, -1
   330  		}
   331  		if n.Right != nil {
   332  			if n.Right.color() == Black && n.Right.Left.color() == Black {
   333  				n = n.moveRedRight()
   334  			}
   335  			if e.Compare(n.Elem) == 0 {
   336  				n.Elem = n.Right.min().Elem
   337  				n.Right, d = n.Right.deleteMin()
   338  			} else {
   339  				n.Right, d = n.Right.delete(e)
   340  			}
   341  		}
   342  	}
   343  
   344  	root = n.fixUp()
   345  
   346  	return
   347  }
   348  
   349  // Return the minimum value stored in the tree. This will be the left-most minimum value if
   350  // insertion without replacement has been used.
   351  func (t *Tree) Min() Comparable {
   352  	if t.Root == nil {
   353  		return nil
   354  	}
   355  	return t.Root.min().Elem
   356  }
   357  
   358  func (n *Node) min() *Node {
   359  	for ; n.Left != nil; n = n.Left {
   360  	}
   361  	return n
   362  }
   363  
   364  // Return the maximum value stored in the tree. This will be the right-most maximum value if
   365  // insertion without replacement has been used.
   366  func (t *Tree) Max() Comparable {
   367  	if t.Root == nil {
   368  		return nil
   369  	}
   370  	return t.Root.max().Elem
   371  }
   372  
   373  func (n *Node) max() *Node {
   374  	for ; n.Right != nil; n = n.Right {
   375  	}
   376  	return n
   377  }
   378  
   379  // Floor returns the greatest value equal to or less than the query q according to q.Compare().
   380  func (t *Tree) Floor(q Comparable) Comparable {
   381  	if t.Root == nil {
   382  		return nil
   383  	}
   384  	n := t.Root.floor(q)
   385  	if n == nil {
   386  		return nil
   387  	}
   388  	return n.Elem
   389  }
   390  
   391  func (n *Node) floor(q Comparable) *Node {
   392  	if n == nil {
   393  		return nil
   394  	}
   395  	switch c := q.Compare(n.Elem); {
   396  	case c == 0:
   397  		return n
   398  	case c < 0:
   399  		return n.Left.floor(q)
   400  	default:
   401  		if r := n.Right.floor(q); r != nil {
   402  			return r
   403  		}
   404  	}
   405  	return n
   406  }
   407  
   408  // Ceil returns the smallest value equal to or greater than the query q according to q.Compare().
   409  func (t *Tree) Ceil(q Comparable) Comparable {
   410  	if t.Root == nil {
   411  		return nil
   412  	}
   413  	n := t.Root.ceil(q)
   414  	if n == nil {
   415  		return nil
   416  	}
   417  	return n.Elem
   418  }
   419  
   420  func (n *Node) ceil(q Comparable) *Node {
   421  	if n == nil {
   422  		return nil
   423  	}
   424  	switch c := q.Compare(n.Elem); {
   425  	case c == 0:
   426  		return n
   427  	case c > 0:
   428  		return n.Right.ceil(q)
   429  	default:
   430  		if l := n.Left.ceil(q); l != nil {
   431  			return l
   432  		}
   433  	}
   434  	return n
   435  }
   436  
   437  // An Operation is a function that operates on a Comparable. If done is returned true, the
   438  // Operation is indicating that no further work needs to be done and so the Do function should
   439  // traverse no further.
   440  type Operation func(Comparable) (done bool)
   441  
   442  // Do performs fn on all values stored in the tree. A boolean is returned indicating whether the
   443  // Do traversal was interrupted by an Operation returning true. If fn alters stored values' sort
   444  // relationships, future tree operation behaviors are undefined.
   445  func (t *Tree) Do(fn Operation) bool {
   446  	if t.Root == nil {
   447  		return false
   448  	}
   449  	return t.Root.do(fn)
   450  }
   451  
   452  func (n *Node) do(fn Operation) (done bool) {
   453  	if n.Left != nil {
   454  		done = n.Left.do(fn)
   455  		if done {
   456  			return
   457  		}
   458  	}
   459  	done = fn(n.Elem)
   460  	if done {
   461  		return
   462  	}
   463  	if n.Right != nil {
   464  		done = n.Right.do(fn)
   465  	}
   466  	return
   467  }
   468  
   469  // DoReverse performs fn on all values stored in the tree, but in reverse of sort order. A boolean
   470  // is returned indicating whether the Do traversal was interrupted by an Operation returning true.
   471  // If fn alters stored values' sort relationships, future tree operation behaviors are undefined.
   472  func (t *Tree) DoReverse(fn Operation) bool {
   473  	if t.Root == nil {
   474  		return false
   475  	}
   476  	return t.Root.doReverse(fn)
   477  }
   478  
   479  func (n *Node) doReverse(fn Operation) (done bool) {
   480  	if n.Right != nil {
   481  		done = n.Right.doReverse(fn)
   482  		if done {
   483  			return
   484  		}
   485  	}
   486  	done = fn(n.Elem)
   487  	if done {
   488  		return
   489  	}
   490  	if n.Left != nil {
   491  		done = n.Left.doReverse(fn)
   492  	}
   493  	return
   494  }
   495  
   496  // DoRange performs fn on all values stored in the tree over the interval [from, to) from left
   497  // to right. If to is less than from DoRange will panic. A boolean is returned indicating whether
   498  // the Do traversal was interrupted by an Operation returning true. If fn alters stored values'
   499  // sort relationships future tree operation behaviors are undefined.
   500  func (t *Tree) DoRange(fn Operation, from, to Comparable) bool {
   501  	if t.Root == nil {
   502  		return false
   503  	}
   504  	if from.Compare(to) > 0 {
   505  		panic("llrb: inverted range")
   506  	}
   507  	return t.Root.doRange(fn, from, to)
   508  }
   509  
   510  func (n *Node) doRange(fn Operation, lo, hi Comparable) (done bool) {
   511  	lc, hc := lo.Compare(n.Elem), hi.Compare(n.Elem)
   512  	if lc <= 0 && n.Left != nil {
   513  		done = n.Left.doRange(fn, lo, hi)
   514  		if done {
   515  			return
   516  		}
   517  	}
   518  	if lc <= 0 && hc > 0 {
   519  		done = fn(n.Elem)
   520  		if done {
   521  			return
   522  		}
   523  	}
   524  	if hc > 0 && n.Right != nil {
   525  		done = n.Right.doRange(fn, lo, hi)
   526  	}
   527  	return
   528  }
   529  
   530  // DoRangeReverse performs fn on all values stored in the tree over the interval (to, from] from
   531  // right to left. If from is less than to DoRange will panic. A boolean is returned indicating
   532  // whether the Do traversal was interrupted by an Operation returning true. If fn alters stored
   533  // values' sort relationships future tree operation behaviors are undefined.
   534  func (t *Tree) DoRangeReverse(fn Operation, from, to Comparable) bool {
   535  	if t.Root == nil {
   536  		return false
   537  	}
   538  	if from.Compare(to) < 0 {
   539  		panic("llrb: inverted range")
   540  	}
   541  	return t.Root.doRangeReverse(fn, from, to)
   542  }
   543  
   544  func (n *Node) doRangeReverse(fn Operation, hi, lo Comparable) (done bool) {
   545  	lc, hc := lo.Compare(n.Elem), hi.Compare(n.Elem)
   546  	if hc > 0 && n.Right != nil {
   547  		done = n.Right.doRangeReverse(fn, hi, lo)
   548  		if done {
   549  			return
   550  		}
   551  	}
   552  	if lc <= 0 && hc > 0 {
   553  		done = fn(n.Elem)
   554  		if done {
   555  			return
   556  		}
   557  	}
   558  	if lc <= 0 && n.Left != nil {
   559  		done = n.Left.doRangeReverse(fn, hi, lo)
   560  	}
   561  	return
   562  }
   563  
   564  // DoMatch performs fn on all values stored in the tree that match q according to Compare, with
   565  // q.Compare() used to guide tree traversal, so DoMatching() will out perform Do() with a called
   566  // conditional function if the condition is based on sort order, but can not be reliably used if
   567  // the condition is independent of sort order. A boolean is returned indicating whether the Do
   568  // traversal was interrupted by an Operation returning true. If fn alters stored values' sort
   569  // relationships, future tree operation behaviors are undefined.
   570  func (t *Tree) DoMatching(fn Operation, q Comparable) bool {
   571  	if t.Root == nil {
   572  		return false
   573  	}
   574  	return t.Root.doMatch(fn, q)
   575  }
   576  
   577  func (n *Node) doMatch(fn Operation, q Comparable) (done bool) {
   578  	c := q.Compare(n.Elem)
   579  	if c <= 0 && n.Left != nil {
   580  		done = n.Left.doMatch(fn, q)
   581  		if done {
   582  			return
   583  		}
   584  	}
   585  	if c == 0 {
   586  		done = fn(n.Elem)
   587  		if done {
   588  			return
   589  		}
   590  	}
   591  	if c >= 0 && n.Right != nil {
   592  		done = n.Right.doMatch(fn, q)
   593  	}
   594  	return
   595  }