struct node {
int key;
int height;
node *lch, *rch;
node (int k) : key(k), height(1), lch(NULL), rch(NULL) {}
};
node *root = NULL;
int Height(node *p) {
return p == NULL? 0 : p->height;
}
void update_height(node *p) {
p->height = max(Height(p->lch), Height(p->rch)) + 1;
}
// rotate right
node *rotate_ll(node *p) {
node *q = p->lch;
p->lch = q->rch; q->rch = p;
update_height(p); update_height(q);
return q;
}
// rotate left
node *rotate_rr(node *p) {
node *q = p->rch;
p->rch = q->lch; q->lch = p;
update_height(p); update_height(q);
}
node *balance(node *p) {
update_height(p);
if (Height(p->rch) - Height(p->lch) > 1) {
node *r = p->rch;
if (Height(r->lch) - Height(r->rch) > 0) p->rch = rotate_ll(p->rch);
return rotate_rr(p);
}
if (Height(p->lch) - Height(p->rch) > 1) {
node *l = p->lch;
if (Height(l->rch) - Height(l->lch) > 0) p->lch = rotate_rr(p->lch);
return rotate_ll(p);
}
return p;
}
node *insert(node *p, int x) {
if (p == NULL) return new node(x);
if (x < p->key) p->lch = insert(p->lch, x);
else p->rch = insert(p->rch, x);
return balance(p);
}
node *findmin(node *p) {
return p->lch == NULL? p : findmin(p->lch);
}
node *removemin(node *p) {
if (p->lch == NULL) return p->rch;
p->lch = removemin(p->lch);
return balance(p);
}
node *remove(node *p, int x) {
if (p == NULL) return NULL;
cout << "node : " << p->key << " x : " << x << endl;
if (x < p->key) p->lch = remove(p->lch, x);
else if (x > p->key) p->rch = remove(p->rch, x);
else // x == p->key
{
node *q = p->lch;
node *r = p->rch;
delete p;
if (r == NULL) return q;
node *min = findmin(r);
min->rch = removemin(r);
min->lch = q;
return balance(min);
}
return balance(p);
}
bool find(node *p, int x) {
if (p == NULL) return false;
else if (p->key == x) return true;
else if (x < p->key) return find(p->lch, x);
else return find(p->rch, x);
}
AVL Tree
最新推荐文章于 2024-11-04 22:46:06 发布