AVL树的一些基本操作


struct node{
	int v,height;//v为结点权值,height为当前子树高度;
	int data;
	node *lchild,*rchild;
}; 
//生成一个新结点,v为结点权值 
node *newNode(int v){
	node *Node=new node;
	Node->height=1;
	Node->v=v;
	Node->lchild=Node->rchild=NULL;
	return Node;
}
//获取以root为根节点的子树的当前的height 
int getHeight(node *root){
	if(root==NULL){
		return 0;//空结点高度为0 
	}
	return root->height;
}
//计算结点root的平衡因子
int getBalanceFactor(node *root){
	//左子树高度减右子树高度
	return getHeight(root->lchild)-getHeight(root->rchild); 
}
//更新结点root的height
void updateHeight(node *root){
	//max(左孩子的height,右孩子的height+1
	root->height=max(getHeight(root->lchild),getHeight(root->rchild))+1; 
} 

//查找 
//search函数查找AVL树中的数据域为x的结点
void search(node *root,int x){
	if(root==NULL){
		printf("search failed ");
		return;
	}
	if(root->v==x){//查找成功,访问之 
		printf("%d\n",root->data);
	}else if(x<root->v){//如果x比根节点的数据域小,说明x在左子树 
		search(root->lchild,x);//往左子树搜索x 
	}else{//如果x比根节点数据域大,说明x在右子树 
		search(root->rchild,x);//往右子树搜索x 
	}
} 

//插入
//左旋(Left Rotation)
void L(node *&root){
	node *temp=root->rchild;//root指向结点A,temp指向结点B
	root->rchild=temp->lchild;//步骤1 
	temp->lchild=root;//步骤2 
	updateHeight(root);//更新结点A的高度 
	updateHeight(temp);//更新结点B的高度 
	root=temp; //步骤3 
} 
//右旋
void R(node *&root){
	node *temp=root->lchild;
	root->lchild=temp->rchild;
	temp->rchild=root;
	updateHeight(root);
	updateHeight(temp);
	root=temp;
} 
//插入权值为v的结点,同时进行平衡操作 
void insert(node *&root,int v){
	if(root==NULL){//到达空结点 
		root=newNode(v);
		return;
	}
	if(v<root->v){//v比根结点的权值小 
		insert(root->lchild,v);//往左子树插入 
		updateHeight(root);//更新树高
		if(getBalanceFactor(root)==2){
			if(getBalanceFavtor(root->lchild)==1){//LL型 
				R(root);//右旋 
			}else if(getBalanceFactor(root->lchild)==-1){//LR
				L(root->lchild);
				R(root);
			}
		}
	}else{//v比根结点权值大 
		insert(root->rchild,x);
		updateHeight(root);
		if(getBalanceFactor(root)==-2){
			if(getBalanceFactor(root->rchild)==-1){//RR型 
				L(root);
			}else if(getBalanceFactor(root->rchild)==1){//RL 
				R(root->rchild);
				L(root);
			}
		}
	}
} 
//AVL树的建立
node *Create(int data[],int n){
	node *root=NULL;//新建空根结点root
	for(int i=0;i<n;i++)
		insert(root,data[i]);
	return root; 
} 

è¿éåå¾çæè¿°è¿éåå¾çæè¿°

发布了51 篇原创文章 · 获赞 7 · 访问量 7449

猜你喜欢

转载自blog.csdn.net/Jason6620/article/details/104082792
今日推荐