自平衡二叉搜索树(AVL)的实现C语言

 

 关键:

1.每插入一个节点或更换节点位置都要更新一次其根节点的高度

2.判断不平衡的条件,左右子树高度差为2

先看avlInsert()函数里的大框架会比较好理解 

#include<stdio.h>
#include<stdlib.h>
typedef struct tree
{
	int data;
	int height;
	struct tree* lchild;
	struct tree* rchild;
}treenode,tree;

int Height(tree* node)
{
    if(node)
        return node->height;
    else
        return 0;
}
    
int max(int a,int b)
{
    if(a>b)
        return a;
    else
        return b;
}
        
    
void llRotation(tree* node,tree** T)
{
	tree* temp = node->lchild;
	node->lchild = temp->rchild ;
	temp->rchild = node;
	*T = temp;
	temp->height = max(Height(temp->lchild ),Height(temp->rchild))+1;
	node->height = max(Height(node->lchild),Height(node->rchild))+1;
	return ;
}

void rrRotation(tree* node,tree** T)
{
	tree* temp = node->rchild;
	node->rchild = temp->lchild ;
	temp->lchild = node;
	*T = temp;
	temp->height = max(Height(temp->lchild ),Height(temp->rchild))+1;
	node->height = max(Height(node->lchild),Height(node->rchild))+1;
	return ;
}

void avlInsert(tree** T,int data)
{
	if(*T==NULL)
	{
		*T = (tree*)malloc(sizeof(tree));
		(*T)->data = data;
		(*T)->lchild = NULL;
		(*T)->rchild = NULL; 
	}
	else if((*T)->data>data)
	{
		avlInsert(&(*T)->lchild,data);
		int lheight = Height((*T)->lchild);
		int rheight = Height((*T)->rchild);
		//判断高度差
		if(lheight-rheight==2)
		{
			if((*T)->lchild->data>data)
			//LL调整
			llRotation(*T,T); 
			else
			//LR调整 
			rrRotation((*T)->lchild,&(*T)->lchild);
			llRotation(*T,&(*T));
		 } 
	}
	else
	{
		avlInsert(&(*T)->rchild,data);
		int lheight = Height((*T)->lchild);
		int rheight = Height((*T)->rchild);
		//判断高度差
		if(rheight-lheight==2)
		{
			if((*T)->rchild->data>data)
			//RL调整
			{
			llRotation((*T)->rchild,&(*T)->rchild); 
			rrRotation(*T,&(*T));
		    }
			else
			//RR调整 
			rrRotation(*T,&(*T));
		 } 
	}
	(*T)->height = max(Height((*T)->lchild),Height((*T)->rchild))+1;
}
void Preorder(tree* T)//前序遍历看看对不对
{
	if(T)
	{
		printf("%d ",T->data );
		Preorder(T->lchild );
		Preorder(T->rchild );
	}
	return ;
}
int main()
{
	tree* T;
	int i;
	int a[5] = {1,2,3,4,5};
	
	for(i = 0;i<5;i++)
	    avlInsert(&T,a[i]);
	Preorder(T);
	printf("\n");
	
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值