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 *), int *new)
87 *n = r = malloc(sizeof **n);
90 r->left = r->right = 0;
100 r = insert(&r->left, k, cmp, new);
102 r = insert(&r->right, k, cmp, new);
108 static struct node *movr(struct node *n, struct node *r) {
111 n->right = movr(n->right, r);
115 static struct node *remove(struct node **n, const void *k,
116 int (*cmp)(const void *, const void *), struct node *parent)
122 c = cmp(k, (*n)->key);
125 *n = movr(r->left, r->right);
130 parent = remove(&(*n)->left, k, cmp, *n);
132 parent = remove(&(*n)->right, k, cmp, *n);
138 void *tdelete(const void *restrict key, void **restrict rootp,
139 int(*compar)(const void *, const void *))
141 /* last argument is arbitrary non-null pointer
142 which is returned when the root node is deleted */
143 return remove((void*)rootp, key, compar, *rootp);
146 void *tfind(const void *key, void *const *rootp,
147 int(*compar)(const void *, const void *))
149 return find(*rootp, key, compar);
152 void *tsearch(const void *key, void **rootp,
153 int (*compar)(const void *, const void *))
156 return insert((void*)rootp, key, compar, &new);
159 static void walk(const struct node *r, void (*action)(const void *, VISIT, int), int d)
163 if (r->left == 0 && r->right == 0)
166 action(r, preorder, d);
167 walk(r->left, action, d+1);
168 action(r, postorder, d);
169 walk(r->right, action, d+1);
170 action(r, endorder, d);
174 void twalk(const void *root, void (*action)(const void *, VISIT, int))
176 walk(root, action, 0);