AVL Tree

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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值