【题目描述】请编程实现伸展树的Insert(插入)和Find(查找)算法。例如,依次插入关键字10、50、40、30、20和60,并以缩进的方式显示得到的伸展树(其中,60是根,它的左孩子是30,右孩子是空,–表示空指针;30的左孩子是20,右孩子是50……),如下所示:
60
30
20
10
--
--
--
50
40
--
--
--
--
在此基础上,再执行查找40的操作,再以缩进的方式显示得到的伸展树,如下所示:
40
30
20
10
--
--
--
--
60
50
--
--
--
可以看到,查找成功后,40被伸展成为根结点。
【输入】
第一行输入关键字的个数n(<20)的值;第二行输入要插入的n个关键字的整数值;第三行输入一个要查找的关键字的值。
【输出】
以缩进的方式显示得到的伸展树。
【输入样例】
6
10 50 40 30 20 60
40
【输出样例】
40
30
20
10
--
--
--
--
60
50
--
--
--
#include<iostream>
using namespace std;
enum ResultCode{Underflow,Overflow,Success,Duplicate,Fail,NotPresent
};
struct TNode{
int element;
TNode *lChild,*rChild;
};
void Lot(TNode *&p){
TNode *r;
r=p->rChild;
p->rChild=r->lChild;
r->lChild=p;
p=r;
}
void Rot(TNode *&p){
TNode *r=p->lChild;
p->lChild=r->rChild;
r->rChild=p;
p=r;
}
ResultCode Insert(TNode *&p,int x){
ResultCode result=Success;
TNode *r;
if(p==NULL){
p=new TNode;
p->element=x;p->lChild=NULL;p->rChild=NULL;
return result;
}
if(p->element==x){
result=Duplicate;
return result;
}
if(x<p->element){
r=p->lChild;
if(r==NULL){
r=new TNode;
r->element=x;r->lChild=NULL;r->rChild=NULL;
r->rChild=p;
p=r;
return result;
}
if(x==r->element){
result=Duplicate;
Rot(p);
return result;
}
if(x<r->element){
result=Insert(r->lChild,x);
Rot(p);
Rot(p);
}else{
result=Insert(r->rChild,x);
Lot(r);
p->lChild=r;
Rot(p);
}
}
else{
r=p->rChild;
if(r==NULL){
r=new TNode;
r->element=x;r->lChild=NULL;r->rChild=NULL;
r->lChild=p;
p=r;
return result;
}
if(x==r->element){
result=Duplicate;
Lot(p);
return result;
}
if(x<r->element){
result=Insert(r->lChild,x);
Rot(r);
p->rChild=r;
Lot(p);
}else{
result=Insert(r->rChild,x);
Lot(p);
Lot(p);
}
}
}
void ShowSpTree(TNode *p,int pos){
int i;
for(i=0;i<pos;i++){
cout<<" ";
}
if(p!=NULL){
cout<<p->element<<endl;
ShowSpTree(p->lChild,pos+5);
ShowSpTree(p->rChild,pos+5);
}else{
cout<<"--"<<endl;
}
}
int main(){
int i,n,x,y;
TNode *p=NULL;
cin>>n;
for(i=0;i<n;i++){
cin>>x;
Insert(p,x);
}
// ShowSpTree(p,0);
cin>>y;
Insert(p,y);
ShowSpTree(p,0);
return 0;
}