您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之查找二:平衡二叉树

2016-12-07 11:02 323 查看
#include<iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
struct bst {
int d;
bst *l,*r;
int deep;
bst() {
l=r=NULL;
deep=0;
}
};
int deept(bst *p) {
if(!p)
return -1;
return p->deep;
}
bst *LL(bst *p) {
bst *q=p->l;
p->l=q->r;
q->r=p;
p->deep=max(deept(p->r),deept(p->l))+1;
q->deep=max(p->deep,deept(q->l))+1;
return q;
}
bst *RR(bst *p) {
bst *q=p->r;
p->r=q->l;
q->l=p;
p->deep=max(deept(p->l),deept(p->r))+1;
q->deep=max(deept(q->r),p->deep)+1;
return q;
}
bst *LR(bst *p) {
p->l=RR(p->l);
return LL(p);
}
bst *RL(bst *p) {
p->r=LL(p->r);
return RR(p);
}
bst *InsertT(bst *p,int k) {
if(!p) {
p=new bst;
p->d=k;
}
else if(k<p->d) {
p->l=InsertT(p->l,k);
if(deept(p->l)-deept(p->r)>1) {
if(k<p->l->d)
p=LL(p);
else
p=LR(p);
}
}
else if(k>p->d) {
p->r=InsertT(p->r,k);
if(deept(p->r)-deept(p->l)>1) {
if(k>p->r->d)
p=RR(p);
else p=RL(p);
}
}
p->deep=max(deept(p->l),deept(p->r))+1;
return p;
}

int main() {
int n;
scanf("%d", &n);
bst *root=NULL;
while(n--) {
int x;
scanf("%d", &x);
root=InsertT(root,x);
}
printf("%d", root->d);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: