2 * Copyright (c) 2010 Joseph Adams <joeyadams3.14159@gmail.com>
4 * Permission to use, copy, modify, and/or distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23 typedef struct AVL AVL;
24 typedef struct AvlNode AvlNode;
25 typedef struct AvlIter AvlIter;
27 typedef int (*AvlCompare)(const void *, const void *);
29 AVL *avl_new(AvlCompare compare);
30 /* Create a new AVL tree sorted with the given comparison function. */
32 void avl_free(AVL *avl);
33 /* Free an AVL tree. */
35 void *avl_lookup(const AVL *avl, const void *key);
36 /* O(log n). Lookup a value at a key. Return NULL if the key is not present. */
38 #define avl_member(avl, key) (!!avl_lookup_node(avl, key))
39 /* O(log n). See if a key is present. */
41 size_t avl_count(const AVL *avl);
42 /* O(1). Return the number of elements in the tree. */
44 bool avl_insert(AVL *avl, const void *key, const void *value);
46 * O(log n). Insert a key/value pair, or replace it if already present.
48 * Return false if the insertion replaced an existing key/value.
51 bool avl_remove(AVL *avl, const void *key);
53 * O(log n). Remove a key/value pair (if present).
55 * Return true if it was removed.
58 bool avl_check_invariants(AVL *avl);
59 /* For testing purposes. This function will always return true :-) */
62 /************************* Traversal *************************/
64 #define avl_foreach(iter, avl) avl_traverse(iter, avl, FORWARD)
66 * O(n). Traverse an AVL tree in order.
73 * printf("%s -> %s\n", i.key, i.value);
76 #define avl_foreach_reverse(iter, avl) avl_traverse(iter, avl, BACKWARD)
77 /* O(n). Traverse an AVL tree in reverse order. */
79 typedef enum AvlDirection {FORWARD = 0, BACKWARD = 1} AvlDirection;
89 AvlDirection direction;
92 void avl_iter_begin(AvlIter *iter, AVL *avl, AvlDirection dir);
93 void avl_iter_next(AvlIter *iter);
94 #define avl_traverse(iter, avl, direction) \
95 for (avl_iter_begin(&(iter), avl, direction); \
96 (iter).node != NULL; \
100 /***************** Internal data structures ******************/
113 int balance; /* -1, 0, or 1 */
116 AvlNode *avl_lookup_node(const AVL *avl, const void *key);
117 /* O(log n). Lookup an AVL node by key. Return NULL if not present. */