伸展树操作

算法描述:
要完成伸展树的插入和查找,先要写出最基础的左旋和右旋操作,因为要把最近操作的一个数旋转到根节点上。
左旋zag:将当前节点的右孩子给父亲节点的左孩子,把父亲节点给当前节点的右孩子。
即:p->lChild=q->rChild;p->rChild=q;
右旋zig:将当前节点的左孩子给父亲节点的右孩子,把父亲节点给当前节点的左孩子。
即:p->rChild=q->lChild;p->lChild=q;

插入操作:分情况讨论:
(1)要插入的节点为空:直接给当前节点赋值。
(2)要插入的值等于当前节点的值,返回已存在。
(3)x小于当前节点,把左孩子变成当前节点。
1)当前节点为空:直接给当前节点赋值。
2)当前节点等于插入的值:进行右旋,将其变为根节点,返回已存在。
3)当前节点小于插入的值:用当前节点左孩子当做根节点进行插入操作(递归),再进行两次右旋(保证操作的在根节点上)。
4)当前节点大于插入的值:用当前节点右孩子当做根节点进行插入操作(递归),再先左旋,再把左孩子变成根节点,进行右旋。
(4)x大于当前节点,把右孩子变成当前节点。操作跟上述操作类似,也分四种情况,不过旋转方向相反。在此不赘述。

查找操作:
查找操作类似于插入,当x==p->element 时,就做一个插入操作,这样能把查找的值翻转到最上面,跟插入的原理相同。当大于的时候,右孩子做递归,小于时,左孩子做递归。

源程序:

#include <iostream>
using namespace std;

enum ResultCode{Underflow,Overflow,Success,Duplicate,Fail,NotPresent};

struct BTNode{
	int element;
	BTNode *lChild,*rChild;
};

void LRot(BTNode *&p){
	BTNode *r=p->rChild;
	p->rChild=r->lChild;
	r->lChild=p;
	p=r;
}

void RRot(BTNode *&p){
	BTNode *r=p->lChild;
	p->lChild=r->rChild;
	r->rChild=p;
	p=r;
}

ResultCode Insert(BTNode *&p,int x){ 
	ResultCode result=Success;
	BTNode *r;
	if(p==NULL){
		p=new BTNode;
		p->element=x;p->lChild=NULL;p->rChild=NULL;
		return result;
	}
	if(x==p->element){
		result=Duplicate;
		return result;
	}
	if(x<p->element){
		r=p->lChild;
		if(r==NULL){
			r=new BTNode;
			r->element=x;r->lChild=NULL;r->rChild=NULL;
			r->rChild=p;p=r;
			return result;
		}
		else if(x==r->element){
			RRot(p);
			result=Duplicate;
			return result;
		}
		if(x<r->element){
			result=Insert(r->lChild,x);
			RRot(p);RRot(p);
		}
		else{
			result=Insert(r->rChild,x);
			LRot(r);
			p->lChild=r;
			RRot(p);
		}
	}
	else{
		r=p->rChild;
		if(r==NULL){
			r=new BTNode;
			r->element=x;r->lChild=NULL;r->rChild=NULL;
			r->lChild=p;p=r;
			return result;
		}
		else if(x==r->element){
			LRot(p);
			result=Duplicate;
			return result;
		}
		if(x>r->element){
			result=Insert(r->rChild,x);
			LRot(p);LRot(p);
		}
		else{
			result=Insert(r->lChild,x);
			RRot(r);
			p->rChild=r;
			LRot(p);
		}
	}
	return result;
}

void Find(BTNode *p,BTNode *&boot,int x){
	if(p==NULL)
		return ;
	if(x==p->element){
		Insert(boot,x);
		return ;
	}		
	if(x<p->element)
		Find(p->lChild,boot,x);
	else
		Find(p->rChild,boot,x);
}


void ShowSPTree(BTNode *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 n,i,x;
	BTNode *boot=NULL;
	ResultCode result=Success;
	cin>>n;
	for(i=0;i<n;i++){
		cin>>x;
		Insert(boot,x);
	}
	cin>>x;
	Find(boot,boot,x);
	ShowSPTree(boot,0);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/jihome/article/details/94965026
今日推荐