5 avl tree implementation using recursive functions
6 the height of an n node tree is less than 1.44*log2(n+2)-1
7 (so the max recursion depth in case of a tree with 2^32 nodes is 45)
17 static int delta(struct node *n) {
18 return (n->left ? n->left->height:0) - (n->right ? n->right->height:0);
21 static void updateheight(struct node *n) {
23 if (n->left && n->left->height > n->height)
24 n->height = n->left->height;
25 if (n->right && n->right->height > n->height)
26 n->height = n->right->height;
30 static struct node *rotl(struct node *n) {
31 struct node *r = n->right;
39 static struct node *rotr(struct node *n) {
40 struct node *l = n->left;
48 static struct node *balance(struct node *n) {
52 if (delta(n->right) > 0)
53 n->right = rotr(n->right);
56 if (delta(n->left) < 0)
57 n->left = rotl(n->left);
64 static struct node *find(struct node *n, const void *k,
65 int (*cmp)(const void *, const void *))
75 return find(n->left, k, cmp);
77 return find(n->right, k, cmp);
80 static struct node *insert(struct node *n, const void *k,
81 int (*cmp)(const void *, const void *), struct node **found)
87 n = malloc(sizeof *n);
90 n->left = n->right = 0;
101 r = insert(c < 0 ? n->left : n->right, k, cmp, found);
112 static struct node *remove_rightmost(struct node *n, struct node **rightmost)
118 n->right = remove_rightmost(n->right, rightmost);
122 static struct node *remove(struct node **n, const void *k,
123 int (*cmp)(const void *, const void *), struct node *parent)
129 c = cmp(k, (*n)->key);
133 r->left = remove_rightmost(r->left, n);
134 (*n)->left = r->left;
135 (*n)->right = r->right;
143 parent = remove(&(*n)->left, k, cmp, *n);
145 parent = remove(&(*n)->right, k, cmp, *n);
151 void *tdelete(const void *restrict key, void **restrict rootp,
152 int(*compar)(const void *, const void *))
156 struct node *n = *rootp;
158 /* last argument is arbitrary non-null pointer
159 which is returned when the root node is deleted */
160 ret = remove(&n, key, compar, n);
165 void *tfind(const void *key, void *const *rootp,
166 int(*compar)(const void *, const void *))
170 return find(*rootp, key, compar);
173 void *tsearch(const void *key, void **rootp,
174 int (*compar)(const void *, const void *))
180 update = insert(*rootp, key, compar, &ret);
186 static void walk(const struct node *r, void (*action)(const void *, VISIT, int), int d)
190 if (r->left == 0 && r->right == 0)
193 action(r, preorder, d);
194 walk(r->left, action, d+1);
195 action(r, postorder, d);
196 walk(r->right, action, d+1);
197 action(r, endorder, d);
201 void twalk(const void *root, void (*action)(const void *, VISIT, int))
203 walk(root, action, 0);