AVL树

struct node
{
	int data,height;
	node *lchild,*rchild;
};
//新建结点 
node *newnode(int x)
{
	node *root=new node;
	root->data=x;
	root->lchild=root->rchild=NULL;
	root->height=1;
	return root;
}
//获取root所在字树的当前高度
int getheight(node *root)
{
	if(root==NULL)
	return 0;
	return root->height;
}
//计算平衡因子
int getbla(node *root)
{
	return getheight(root->lchild)-getheight(root->rchild);
} 
//更新结点高度
void upheight(node *root)
{//root所在子树的高度等于其左子树和右子树的高度较大的+1 
	root->height=max(getheight(root->lchild),getheight(root->rchild))+1;
} 
//左旋
void left(node *&root)
{
	node *temp=root->rchild;
	root->rchild=temp->lchild; //左旋根右转   
	temp->lchild=root;
	upheight(root);
	upheight(temp);
	root=temp;
} 
void right(node *&root)
{
	node *temp=root->lchild;
	root->lchild=temp->rchild; //左旋根右转   
	temp->rchild=root;
	upheight(root);
	upheight(temp);
	root=temp;
} 
//难点  插入权值为v的  且要考虑平衡因子
void insert(node* &root,int v)
{
	if(root==NULL)
	{
		root=newnode(v);
		return;
	}
	if(v<root->data)//比根小 插左边
	{
		insert(root->lchild,v);
		upheight(root);//更新树高
		if(getheight(root)==2)
		{
			if(getbla(root->lchild)==1)//LL型 
			right(root);
			else if(getbla(root->lchild)==-1)//LR型
			{
				left(root->lchild);
				right(root);
			} 
		} 
	} 
	else//大 插右边 
	{
		insert(root->rchild,v);
		upheight(root);
		if(getheight(root)==-2)
		{
			if(getbla(root->rchild)==-1)//LL型 
			left(root);
			else if(getbla(root->rchild)==1)//LR型
			{
				right(root->rchild);
				left(root);
			} 
		} 
	}
} 
//建树
node *creat(int x[],int n)
{
	node *root=NULL;
	for(int i=0;i<n;i++)
	insert(root,x[i]);
	return root;
} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值