平衡二叉树的实现

平衡二叉树是对排序二叉树的优化,在插入结点时有着很大的变化,需要调整树的高度达到平衡,下面是代码:

#include<iostream>
using namespace std;

struct node{
	int v,height; //height 记录高度 这里的高度是从下往上记 
	node *lchild,*rchild;
};

node* newnode(int x){   //生成一个新结点 
	node* r=new node;
	r->v=x;
	r->height=1;      //初始化高度为一 
	r->lchild=r->rchild=NULL;
	return r;
}

int getheight(node* root) {  // 得到当前结点的高度 
	if(root==NULL)return 0;
	return root->height;
}

int getfactor(node* root){  //得到平衡因子 
	return getheight(root->lchild)-getheight(root->rchild);
}

void updateheight(node* root) {  //更新结点当前高度 
root->height=max(getheight(root->lchild),getheight(root->rchild))+1;
	//左右子树较大者加一 
}


void search(node* root,int x) { // 查找操作不变 
	
	if(root==NULL){  //没有查到 
		printf("fail!\n");
		return;
	}
	if(root->v==x){ //查到 
		printf("succeed!");
		return;
	}
	if(root->v>x)search(root->lchild,x);
	else search(root->rchild,x);
}


//为实现插入操作的四个旋
void L(node* &root) {//左旋,root的右孩子当根 
	node* temp=root->rchild;
	root->rchild=temp->lchild; 
	temp->lchild=root; 
	//更新这两个结点高度 
	updateheight(root);
	updateheight(temp);
	root=temp;//改变根结点 
}

void R(node* &root) {//右旋,root的左孩子当根 
	node* temp=root->lchild;
	root->lchild=temp->rchild;
	temp->rchild=root; 
	updateheight(root);
	updateheight(temp);
	root=temp;
}
/*四种树形结论,看平衡因子 
根为2 左孩子为1,LL型      右旋解决 
      左孩子为 -1,LR型    先左孩子左旋后root右旋解决 
根为-2  右孩子-1,RR型   左旋解决 
        右孩子1,RL型    先右孩子右旋再root左旋解决
*/		
void insert(node* &root,int x){
	if(root==NULL){
	root=newnode(x);
	return;	
	}
	if(x<root->v) {
		insert(root->lchild,x);//往左子树插 
		updateheight(root);//更新高度
		if(getfactor(root)==2) {
			if(getfactor(root->lchild)==1)//LL型,右旋 
			R(root) ;
			else { //LR型,左右旋 
				L(root->lchild) ;
				R(root);
			}
		}
	}
	else{
		insert(root->rchild,x);//往右子树插 
		updateheight(root);//更新高度
		if(getfactor(root)==-2) {
			if(getfactor(root->rchild)==-1)//RR型,左旋 
			L(root) ;
			else { //RL型,右左旋 
				R(root->rchild) ;
				L(root);
			}
		}
	}
}

node * creating(int a[],int n){  //创建二叉树 
	node* root=NULL;
	for(int i=0;i<n;i++)
	insert(root,a[i]);
	return root;	
}


int main(){
	
	return 0;
} 

这里和排序二叉树的区别在于引入了高度好标记平衡因子,高度的更新操作比较重要,之后左、右旋,记录树形解决方法也是难点。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值