avl树的C语言实现(图解+注释)

接口

#include <stdio.h>
#include <stdlib.h>

typedef struct treeNode {
	int data;
	struct treeNode* lchild;
	struct treeNode* rchild;
	int height;
}treeNode;
int getHeight(treeNode* node);
void llRotation(treeNode* node, treeNode** root);
void rrRotation(treeNode* node, treeNode** root);
void avlInsert(treeNode** T, int data);
void preOrder(treeNode* T);

接口实现

#include "avl.h"
int getHeight(treeNode* node){
	return node ? node->height : 0;
}
int getMax(int a,int b) {
	return a > b ? a : b;
}
void llRotation(treeNode*node,treeNode**root) {

	treeNode* temp = node->lchild;
	node->lchild = temp->rchild;
	temp->rchild = node;
	//调整高度
	node->height = getMax(getHeight(node->lchild), getHeight(node->rchild)) + 1;
	temp->height = getMax(getHeight(temp->lchild), getHeight(temp->rchild)) + 1;

	*root = temp;
}
void rrRotation(treeNode* node, treeNode** root) {
	treeNode* temp = node->rchild;
	node->rchild = temp->lchild;
	temp->lchild = node;
	//调整高度
	node->height = getMax(getHeight(node->lchild), getHeight(node->rchild)) + 1;
	temp->height = getMax(getHeight(temp->lchild), getHeight(temp->rchild)) + 1;

	*root = temp;
}



void avlInsert(treeNode** T,int data){
	if (*T == NULL) {
		*T = (treeNode*)malloc(sizeof(treeNode));
		(*T)->data = data;
		(*T)->height = 0;
		(*T)->lchild = NULL;
		(*T)->rchild = NULL;
	}
	else if(data<(*T)->data){
		//插在左边
		avlInsert(&(*T)->lchild, data);
		//获得左右子树的高度
		int lheight = getHeight((*T)->lchild);
		int rheight = getHeight((*T)->rchild);
		//判断高度差
		if (lheight - rheight==2) {
			//此时需要调整
			//
			//在进行判断为LL还是LR
			if (data<(*T)->lchild->data) {
				//此时为LL调整
				llRotation(*T,T);
			}
			else {
				//此时为LR调整
				rrRotation((*T)->lchild, &(*T)->lchild);
				llRotation(*T, T);
			}
		}
	}
	else if (data > (*T)->data) {
		//插在右边
		avlInsert(&(*T)->rchild, data);
		//获得左右子树的高度
		int lheight = getHeight((*T)->lchild);
		int rheight = getHeight((*T)->rchild);
		if (rheight - lheight == 2) {
			//此时需要调整
			//
			//在进行判断为LL还是LR
			if (data > (*T)->rchild->data) {
				//此时为RR调整
				rrRotation(*T, T);
			}
			else {
				//此时为RL调整
				llRotation((*T)->rchild, &(*T)->rchild);
				rrRotation(*T, T);
			}
		}
	}
	else {
		return;
	}
	(*T)->height = getMax(getHeight((*T)->lchild), getHeight((*T)->rchild)) + 1;//调整高度

}
void preOrder(treeNode*T) {
	if (T) {
		printf("%d ", T->data);
		preOrder(T->lchild);
		preOrder(T->rchild);
	}
}


测试

#include "avl.h"
int main() {

	treeNode* T = NULL;
	int nums[5] = { 8,7,9,5,6 };
	for (int i = 0; i < 5; i++) {
		avlInsert(&T, nums[i]);
	}
	preOrder(T);
	printf("\n");
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

1YC..

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值