I’m currently implementing avl trees. After correcting the insertion procedure, I went to implement another procedure to delete a given node from the avl tree. But I’m really stuck. It’s not that I don’t understand how it works, or how to implement it, but I really care about the code complexity, and the delete function as I have thought it is REALLY difficult to implement. Could someone point me to short and understandable implementation of the delete function in avl trees?
Here is my code so far:
struct avl_tree {
private:
struct node {
node *l, *r;
int h, size;
key_t key;
node( key_t k ) : l( 0 ), r( 0 ), h( 1 ), size( 1 ), key( k ) {}
void u() {
h=1+std::max( ( l?l->h:0 ), ( r?r->h:0 ) );
size=( l?l->size:0 ) + ( r?r->size:0 ) + 1;
}
} *root;
compare_t cmp;
int h( node *x ) { return ( x?x->h:0 ); }
node* rotl( node *x ) {
node *y=x->r;
x->r=y->l;
y->l=x;
x->u(); y->u();
return y;
}
node* rotr( node *x ) {
node *y=x->l;
x->l=y->r;
y->r=x;
x->u(); y->u();
return y;
}
node* balance( node *x ) {
x->u();
if( h( x->l ) > 1 + h( x->r ) ) {
if( h( x->l->l ) < ( x->l?h( x->l->r ):0 ) ) x->l = rotl( x->l );
x = rotr( x );
} else if( h( x->r ) > 1 + h( x->l ) ) {
if( h( x->r->r ) < ( x->r?h( x->r->l ): 0 ) ) x->r = rotr( x->r );
x = rotl( x );
}
return x;
}
node* _insert( node *t, key_t k ) {
if( t==NULL ) return new node( k );
if( cmp( k, t->key ) ) { t->l = _insert( t->l, k ); }
else { t->r = _insert( t->r, k ); }
return balance( t );
}
void _inorder( node *t ) {
if( t ) {
_inorder( t->l );
std::cout << t->key << " ";
_inorder( t->r );
}
}
node* _find( node *t, key_t k ) {
if( !t ) return t;
if( cmp( t->key, k ) ) return _find( t->l, k );
else if( cmp( k, t->key ) ) return _find( t->r, k );
else return t;
}
node* _min( node *t ) {
if( !t || !t->l ) return t;
else return _min( t->l );
}
node* _max( node *t ) {
if( !t || !t->r ) return t;
else return _max( t->r );
}
public:
avl_tree() : root( 0 ) {}
void insert( key_t k ) { root = _insert( root, k ); }
void inorder() { _inorder( root ); }
node* find( key_t k ) { return _find( root, k ); }
node* min() { return _min( root ); }
node* max() { return _max( root ); }
};
So, if you understand how deletion from AVL-tree works, I just want to say a few words about complexity of this code. Of course it’s asymptotically optimal O(log n), but constant is not the best. You can replace calls of _extractmin and _min into one function. That will work in one pass by returning pair of two pointers (min and result of balance).