8 avlprev \- Balanced binary search tree routines
10 .ta 0.75i 1.5i 2.25i 3i 3.75i 4.5i
11 .\" .ta 0.7i +0.7i +0.7i +0.7i +0.7i +0.7i +0.7i
17 typedef struct Avl Avl;
18 typedef struct Avltree Avltree;
21 Avl *c[2]; /* children */
23 schar balance; /* balance factor */
26 int (*cmp)(Avl*, Avl*);
30 Avltree *avlcreate(int(*cmp)(Avl*, Avl*));
31 Avl *avlinsert(Avltree *tree, Avl *new);
32 Avl *avldelete(Avltree *tree, Avl *key);
33 Avl *avllookup(Avltree *tree, Avl *key, int dir);
39 These routines allow creation and maintenance of in-memory balanced
42 An empty tree is created by calling
44 with a comparison function as an argument.
45 The comparison function must take two pointers to
47 structures and return an integer less than, equal to, or
48 greater than 0 as the first is
49 respectively less than,
50 equal to, or greater than the second.
54 node into the tree and returns an existing
55 node with the same key that has been removed
56 from the tree and may be freed.
58 searches for a given key and returns
59 the closest node less than the given key,
61 or the closest node greater than the key depending on whether
63 is less than, equal to, or greater than zero, respectively.
65 removes the node matching the key from the tree and returns
66 it. It returns nil if no matching key is found.
73 returns the maximum node.
77 node in an in-order walk of the AVL tree
80 returns the previous node.
82 Intended usage is to embed the
84 structure anonymously.
85 For example, the following will create a key-value store
86 with strings as keys and integers as values.
96 nodecmp(Avl *la, Avl *lb)
102 return strcmp(a->key, b->key);
106 get(Avltree *t, char *key)
111 h = (Node*)avllookup(t, &n);
112 return h ? h->val : -1;
115 Avltree *t = avlcreate(nodecmp);
122 Donald Knuth, ``The Art of Computer Programming'', Volume 3. Section 6.2.3
125 returns nil on error.
127 This implementation was written for 9front (Dec, 2016).