AVL Trees
Jan Dvořák <mordae@anilinux.org>
(require avl) | package: avl |
A self-balancing binary search tree variant.
All mutations of the AVL tree create new nodes instead of modifying the data in place. The imperative variants change the root node in place for convenience. Mutating the tree is not thread-safe.
These trees could be used for as priority queues with possibility to remove elements from the middle.
1 Creating Trees
procedure
<=? : procedure?
procedure
(make-avleq <=?) → avl?
<=? : procedure?
procedure
(make-avleqv <=?) → avl?
<=? : procedure?
Like hash tables, every AVL tree variant uses a different equality predicate. make-avl uses equal?, make-avleq uses eq? and make-avleqv uses eqv?.
Tree with number? elements would use <= as the comparator, tree with string? elements would use string<=? and so on.
> (define tree (make-avleqv <=))
> (avl-add! tree 42)
procedure
(make-custom-avl <=? =?) → avl?
<=? : procedure? =? : procedure?
> (define custom-avl (make-custom-avl (λ (x y) (<= (car x) (car y))) (λ (x y) (equal? (car x) (car y)))))
> (avl-add! custom-avl (cons 1 'hello))
> (avl-add! custom-avl (cons 2 'ciao))
> (avl-add! custom-avl (cons 1 'bye))
> (avl->list custom-avl) '((1 . bye) (2 . ciao))
> (define copy (avl-copy tree))
> (avl-remove! copy 42)
2 Predicates
procedure
(avl-equal? v) → boolean?
v : any/c
procedure
v : any/c
procedure
v : any/c
> (avl-equal? tree) #f
> (avl-eqv? tree) #t
> (avl-eq? tree) #f
procedure
(avl-empty? tree) → boolean?
tree : avl?
> (avl-empty? tree) #f
> (avl-empty? copy) #t
procedure
(avl-contains? tree value) → boolean?
tree : avl? value : any/c
> (avl-contains? tree 42) #t
> (avl-contains? copy 42) #f
3 Manipulating Values
> (let ((new-tree (avl-add tree 13))) (avl-contains? new-tree 13)) #t
> (avl-contains? tree 13) #f
> (avl-add! tree 13)
> (avl-contains? tree 13) #t
procedure
(avl-remove tree value) → avl?
tree : avl? value : any/c
> (let ((new-tree (avl-remove tree 13))) (avl-contains? new-tree 13)) #f
> (avl-contains? tree 13) #t
procedure
(avl-remove! tree value) → void?
tree : avl? value : any/c
> (avl-remove! tree 13)
> (avl-contains? tree 13) #f
4 Queue Usage
procedure
(avl-pop-min tree) →
any/c avl? tree : avl?
> (avl-pop-min tree)
21
#<avl>
> (avl-min tree) 21
procedure
(avl-pop-min! tree) → any/c
tree : avl?
> (avl-pop-min! tree) 21
> (avl-min tree) 42
procedure
(avl-pop-max tree) →
any/c avl? tree : avl?
> (avl-pop-max tree)
101
#<avl>
> (avl-max tree) 101
procedure
(avl-pop-max! tree) → any/c
tree : avl?
> (avl-pop-max! tree) 101
> (avl-max tree) 42
5 Iterating Over Values
procedure
(in-avl/reverse tree) → sequence?
tree : avl?
> (for/list ((value (in-avl/reverse tree))) (/ value 10)) '(21/5)