0
点赞
收藏
分享

微信扫一扫

C++AVL

蓝哆啦呀 2022-03-11 阅读 16
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define HEIGHT(p) ((p==NULL)?-1:(p->height))
#define MAX(a,b) ((a)>(b)?(a):(b))
typedef struct 
{
	int key;
	char info[20];
}DATA,*LPDATA;

typedef struct AVLTreeNode 
{
	DATA data;
	int height;
	struct AVLTreeNode* LChild;
	struct AVLTreeNode* RChild;
}NODE,*LPNODE,*AVLTree;
//创建节点
LPNODE  createNode(DATA data) 
{
	LPNODE newNode = (LPNODE)malloc(sizeof(NODE));
	assert(newNode);
	newNode->data = data;
	newNode->height = 0;
	newNode->LChild = NULL;
	newNode->RChild = NULL;
	return newNode;
}
//打印当前节点中数据
void printCurNode(LPNODE curNode) 
{
	printf("%d:%s\t高度:%d\n", curNode->data.key, 
		curNode->data.info, curNode->height);
}
//前序遍历
void preOrder(AVLTree root) 
{
	if (root != NULL) 
	{
		printCurNode(root);
		preOrder(root->LChild);
		preOrder(root->RChild);
	}
}
//四种旋转操作
//LL:右旋
LPNODE LL_Rotation(LPNODE k2)
{
	//旋转
	LPNODE k1 = k2->LChild;
	k2->LChild = k1->RChild;
	k1->RChild = k2;

	//高度处理
	k2->height = MAX(HEIGHT(k2->LChild), HEIGHT(k2->RChild)) + 1;
	k1->height = MAX(HEIGHT(k1->LChild), k2->height) + 1;
	return k1;   //方便处理原来k2父节点的指针,因为现在k1替换k2的位置
}
//RR:左旋
LPNODE RR_Rotation(LPNODE k1) 
{
	LPNODE  k2=k1->RChild;
	k1->RChild = k2->LChild;
	k2->LChild = k1;

	k1->height = MAX(HEIGHT(k1->LChild), HEIGHT(k1->RChild)) + 1;
	k2->height = MAX(HEIGHT(k2->RChild), k1->height) + 1;
	return k2;
}
//LR:左旋+右旋
LPNODE LR_Rotation(LPNODE k3) 
{
	k3->LChild = RR_Rotation(k3->LChild);
	return LL_Rotation(k3);
}
//RL:右旋+左旋
LPNODE RL_Rotation(LPNODE k3) 
{
	k3->RChild = LL_Rotation(k3->RChild);
	return RR_Rotation(k3);
}
AVLTree insertNode(AVLTree tree, DATA data)
{
	if (tree == NULL)
	{
		tree = createNode(data);
	}
	else if (data.key < tree->data.key)//左边
	{
		tree->LChild = insertNode(tree->LChild, data);
		if (HEIGHT(tree->LChild) - HEIGHT(tree->RChild) == 2)
		{
			if (data.key < tree->LChild->data.key)
			{
				tree = LL_Rotation(tree);
			}
			else
			{
				tree = LR_Rotation(tree);
			}
		}
	}
	else if (data.key > tree->data.key)//右边
	{
		tree->RChild = insertNode(tree->RChild, data);
		if (HEIGHT(tree->RChild) - HEIGHT(tree->LChild) == 2)
		{
			if (data.key > tree->RChild->data.key)
			{
				tree = RR_Rotation(tree);
			}
			else
			{
				tree = RL_Rotation(tree);
			}
		}
	}
	else
	{
		printf("键唯一,无法插入");
	}

	tree->height = MAX(HEIGHT(tree->LChild), HEIGHT(tree->RChild)) + 1;
	return tree;
}
举报

相关推荐

0 条评论