github.com/djordje200179/extendedlibrary/datastructures@v1.7.1-0.20240227175559-d09520a92dd4/maps/rbt/tree.go (about)

     1  package rbt
     2  
     3  import (
     4  	"cmp"
     5  	"github.com/djordje200179/extendedlibrary/datastructures/iter"
     6  	"github.com/djordje200179/extendedlibrary/datastructures/maps"
     7  	"github.com/djordje200179/extendedlibrary/datastructures/seqs/colseq"
     8  	"github.com/djordje200179/extendedlibrary/misc"
     9  	"github.com/djordje200179/extendedlibrary/misc/functions/comparison"
    10  )
    11  
    12  // Tree is a red-black tree implementation of a map.
    13  // The zero value is ready to use. Do not copy a non-zero Tree.
    14  type Tree[K, V any] struct {
    15  	root  *Node[K, V]
    16  	nodes int
    17  
    18  	comparator comparison.Comparator[K]
    19  }
    20  
    21  // NewWithComparator creates an empty Tree with the specified comparator.
    22  func NewWithComparator[K, V any](comparator comparison.Comparator[K]) *Tree[K, V] {
    23  	return &Tree[K, V]{
    24  		comparator: comparator,
    25  	}
    26  }
    27  
    28  // New creates an empty Tree with the default comparator for ordered keys.
    29  func New[K cmp.Ordered, V any]() *Tree[K, V] {
    30  	return NewWithComparator[K, V](cmp.Compare[K])
    31  }
    32  
    33  // NewWithComparatorFromIterable creates a Tree with the specified comparator from the specified iter.Iterable.
    34  func NewWithComparatorFromIterable[K, V any](comparator comparison.Comparator[K], iterable iter.Iterable[misc.Pair[K, V]]) *Tree[K, V] {
    35  	tree := NewWithComparator[K, V](comparator)
    36  
    37  	for it := iterable.Iterator(); it.Valid(); it.Move() {
    38  		entry := it.Get()
    39  		tree.Set(entry.First, entry.Second)
    40  	}
    41  
    42  	return tree
    43  }
    44  
    45  // NewFromIterable creates a Tree from the specified iter.Iterable.
    46  func NewFromIterable[K cmp.Ordered, V any](iterable iter.Iterable[misc.Pair[K, V]]) *Tree[K, V] {
    47  	tree := New[K, V]()
    48  
    49  	for it := iterable.Iterator(); it.Valid(); it.Move() {
    50  		entry := it.Get()
    51  		tree.Set(entry.First, entry.Second)
    52  	}
    53  
    54  	return tree
    55  }
    56  
    57  // Size returns the number of entries in the tree.
    58  func (tree *Tree[K, V]) Size() int {
    59  	return tree.nodes
    60  }
    61  
    62  // GetNode returns the node associated with the specified key.
    63  // Returns nil if the key is not present.
    64  func (tree *Tree[K, V]) GetNode(key K) *Node[K, V] {
    65  	for curr := tree.root; curr != nil; {
    66  		switch tree.comparator(key, curr.key) {
    67  		case comparison.FirstSmaller:
    68  			curr = curr.leftChild
    69  		case comparison.FirstBigger:
    70  			curr = curr.rightChild
    71  		case comparison.Equal:
    72  			return curr
    73  		}
    74  	}
    75  
    76  	return nil
    77  }
    78  
    79  // Contains returns true if the tree contains the specified key.
    80  func (tree *Tree[K, V]) Contains(key K) bool {
    81  	return tree.GetNode(key) != nil
    82  }
    83  
    84  // TryGet returns the value associated with the specified key,
    85  // or zero value and false if the key is not present.
    86  func (tree *Tree[K, V]) TryGet(key K) (V, bool) {
    87  	node := tree.GetNode(key)
    88  	if node == nil {
    89  		var zero V
    90  		return zero, false
    91  	}
    92  
    93  	return node.Value, true
    94  }
    95  
    96  // Get returns the value associated with the specified key.
    97  // Panics if the key is not present.
    98  func (tree *Tree[K, V]) Get(key K) V {
    99  	return *tree.GetRef(key)
   100  }
   101  
   102  // GetRef returns a reference to the value associated with the specified key.
   103  // Panics if the key is not present.
   104  func (tree *Tree[K, V]) GetRef(key K) *V {
   105  	node := tree.GetNode(key)
   106  	if node == nil {
   107  		panic(maps.MissingKeyError[K]{Key: key})
   108  	}
   109  
   110  	return &node.Value
   111  }
   112  
   113  // Set sets the value associated with the specified key.
   114  func (tree *Tree[K, V]) Set(key K, value V) {
   115  	if tree.root == nil {
   116  		tree.root = &Node[K, V]{
   117  			key:   key,
   118  			Value: value,
   119  			color: black,
   120  		}
   121  
   122  		tree.nodes++
   123  
   124  		return
   125  	}
   126  
   127  	var prev *Node[K, V]
   128  	for curr := tree.root; curr != nil; {
   129  		prev = curr
   130  		switch tree.comparator(key, curr.key) {
   131  		case comparison.FirstSmaller:
   132  			curr = curr.leftChild
   133  		case comparison.FirstBigger:
   134  			curr = curr.rightChild
   135  		case comparison.Equal:
   136  			curr.Value = value
   137  			return
   138  		}
   139  	}
   140  
   141  	node := &Node[K, V]{
   142  		key:    key,
   143  		Value:  value,
   144  		parent: prev,
   145  		color:  red,
   146  	}
   147  
   148  	if tree.comparator(key, prev.key) == comparison.FirstSmaller {
   149  		prev.leftChild = node
   150  	} else {
   151  		prev.rightChild = node
   152  	}
   153  
   154  	tree.nodes++
   155  
   156  	tree.fixInsert(node)
   157  }
   158  
   159  func (tree *Tree[K, V]) removeNode(node *Node[K, V]) {
   160  	if node.leftChild != nil && node.rightChild != nil {
   161  		next := node.Next()
   162  
   163  		next.key = node.key
   164  		next.Value = node.Value
   165  
   166  		tree.removeNode(next)
   167  
   168  		return
   169  	}
   170  
   171  	tree.nodes--
   172  
   173  	var child *Node[K, V]
   174  	if node.leftChild != nil {
   175  		child = node.leftChild
   176  	} else {
   177  		child = node.rightChild
   178  	}
   179  
   180  	var locationInParent **Node[K, V]
   181  	if node.parent == nil {
   182  		locationInParent = &tree.root
   183  	} else if node.parent.leftChild == node {
   184  		locationInParent = &node.parent.leftChild
   185  	} else {
   186  		locationInParent = &node.parent.rightChild
   187  	}
   188  
   189  	if child != nil {
   190  		child.parent = node.parent
   191  		*locationInParent = child
   192  
   193  		if node.color == black {
   194  			tree.fixRemove(child)
   195  		}
   196  	} else if node.parent == nil {
   197  		*locationInParent = nil
   198  	} else {
   199  		if node.color == black {
   200  			tree.fixRemove(node)
   201  		}
   202  
   203  		if node.parent != nil {
   204  			if node.parent.leftChild == node {
   205  				node.parent.leftChild = nil
   206  			} else {
   207  				node.parent.rightChild = nil
   208  			}
   209  
   210  			node.parent = nil
   211  		}
   212  	}
   213  }
   214  
   215  // Remove removes the entry with the specified key.
   216  // Does nothing if the key is not present.
   217  func (tree *Tree[K, V]) Remove(key K) {
   218  	node := tree.GetNode(key)
   219  	if node != nil {
   220  		tree.removeNode(node)
   221  	}
   222  }
   223  
   224  // Clear removes all entries from the tree.
   225  func (tree *Tree[K, V]) Clear() {
   226  	tree.root = nil
   227  }
   228  
   229  // Clone returns a shallow copy of the tree.
   230  func (tree *Tree[K, V]) Clone() maps.Map[K, V] {
   231  	newTree := &Tree[K, V]{
   232  		nodes:      tree.nodes,
   233  		comparator: tree.comparator,
   234  	}
   235  
   236  	if tree.root == nil {
   237  		return newTree
   238  	}
   239  
   240  	newTree.root = tree.root.Clone()
   241  
   242  	nodesInOriginal := colseq.NewArrayDeque[*Node[K, V]]()
   243  	nodesInOriginal.PushBack(tree.root)
   244  
   245  	nodesInCloned := colseq.NewArrayDeque[*Node[K, V]]()
   246  	nodesInCloned.PushBack(newTree.root)
   247  
   248  	for !nodesInOriginal.Empty() {
   249  		nodeInOriginal := nodesInOriginal.PopFront()
   250  		nodeInCloned := nodesInCloned.PopFront()
   251  
   252  		if leftNode := nodeInOriginal.leftChild; leftNode != nil {
   253  			nodesInOriginal.PushBack(leftNode)
   254  
   255  			newLeftNode := leftNode.Clone()
   256  			nodeInCloned.leftChild = newLeftNode
   257  			newLeftNode.parent = nodeInCloned
   258  		}
   259  
   260  		if rightNode := nodeInOriginal.rightChild; rightNode != nil {
   261  			nodesInOriginal.PushBack(rightNode)
   262  
   263  			newRightNode := rightNode.Clone()
   264  			nodeInCloned.rightChild = newRightNode
   265  			newRightNode.parent = nodeInCloned
   266  		}
   267  	}
   268  
   269  	return newTree
   270  }
   271  
   272  // Iterator returns an iter.Iterator over the tree.
   273  func (tree *Tree[K, V]) Iterator() iter.Iterator[misc.Pair[K, V]] {
   274  	return tree.MapIterator()
   275  }
   276  
   277  // MapIterator returns an iterator over the tree.
   278  func (tree *Tree[K, V]) MapIterator() maps.Iterator[K, V] {
   279  	return &Iterator[K, V]{tree, tree.root.Min()}
   280  }
   281  
   282  // Stream2 streams over the entries in the Tree.
   283  func (tree *Tree[K, V]) Stream2(yield func(K, V) bool) {
   284  	for it := tree.MapIterator(); it.Valid(); it.Move() {
   285  		if !yield(it.Key(), it.Value()) {
   286  			return
   287  		}
   288  	}
   289  }
   290  
   291  // RefsStream2 streams over the keys and references to the values in the Map.
   292  func (tree *Tree[K, V]) RefsStream2(yield func(K, *V) bool) {
   293  	for it := tree.MapIterator(); it.Valid(); it.Move() {
   294  		if !yield(it.Key(), it.ValueRef()) {
   295  			return
   296  		}
   297  	}
   298  }
   299  
   300  // Root returns the root node of the tree.
   301  func (tree *Tree[K, V]) Root() *Node[K, V] {
   302  	return tree.root
   303  }