diff --git a/src/search/tsearch_avl.c b/src/search/tsearch_avl.c index 8620092..e53cf32 100644 --- a/src/search/tsearch_avl.c +++ b/src/search/tsearch_avl.c @@ -105,11 +105,17 @@ static struct node *insert(struct node **n, const void *k, return r; } -static struct node *movr(struct node *n, struct node *r) { - if (!n) - return r; - n->right = movr(n->right, r); - return balance(n); +static struct node *poprightmost(struct node **p, struct node *n) +{ + struct node *r; + + if (!n->right) { + *p = n->left; + return n; + } + r = poprightmost(&n->right, n->right); + *p = balance(n); + return r; } static struct node *remove(struct node **n, const void *k, @@ -122,7 +128,13 @@ static struct node *remove(struct node **n, const void *k, c = cmp(k, (*n)->key); if (c == 0) { struct node *r = *n; - *n = movr(r->left, r->right); + if (r->left) { + *n = poprightmost(&r->left, r->left); + (*n)->left = r->left; + (*n)->right = r->right; + *n = balance(*n); + } else + *n = r->right; free(r); return parent; }