Debian Codegraph @

trees/avltree/avltree.go

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