相关函数及定义:
#include <stdio.h>
#include <windows.h>
/*--------------------平衡二叉树(AVL)---------------------*/
//左右子树高度差超过 1
typedef struct TreeNode
{
int data;
int height;
struct TreeNode *lchild;
struct TreeNode *rchild;
}TreeNode;
void AVL_insert(TreeNode **T,int data);
void Preorder(TreeNode *T);
int GetHeight(TreeNode *node);
//调整 LL型
//
void LLRotation(TreeNode *node,TreeNode **root);
//调整 RR型
// 取中间结点,使它的父结点作为它的左孩子,如果他有左孩子,则将左孩子作为父亲结点的右孩子
void RRRotation(TreeNode *node,TreeNode **root);
//调整LR型
// 取最后一个结点作为父结点,
// 将它的父结点作为自己的左孩子,将父结点的父结点作为自己的右孩子,
// 如果自己有左孩子或者右孩子,将自己的左孩子连接到父结点的右孩子上,自己的右孩子连接到父结点的父结点的左孩子上
void LLRotation(TreeNode *node,TreeNode **root);
//调整RL型
// 取最后一个结点作为父结点,
// 将它的父结点作为自己的右孩子,将父结点的父结点作为自己的左孩子
// 如果自己有左孩子或者右孩子,将自己的左孩子连接到父结点的父结点的右孩子上,自己的右孩子连接到父结点的左孩子上
void LLRotation(TreeNode *node,TreeNode **root);
int Max(int a,int b);
完整程序:
#include "Balance_tree.h"
void main()
{
TreeNode *T = NULL;
int nums[5] = {1,2,3,4,5};
for(int i = 0;i < 5;i++)
{
AVL_insert(&T,nums[i]);
}
Preorder(T);
printf("\n");
system("pause");
return ;
}
void AVL_insert(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)
{
AVL_insert(&(*T)->lchild,data);
//拿到当前结点的左右子树高度
int lHeight = GetHeight((*T)->lchild);
int rHeight = GetHeight((*T)->rchild);
//判断高度差
if(lHeight - rHeight == 2)
{
if(data < (*T)->lchild->data)
{
//LL型
LLRotation(*T,T);
}
else
{
//LR型
RRRotation((*T)->lchild,&(*T)->lchild);
LLRotation(*T,T);
}
}
}
else if(data > (*T)->data)
{
AVL_insert(&(*T)->rchild,data);
//拿到当前结点的左右子树高度
int lHeight = GetHeight((*T)->lchild);
int rHeight = GetHeight((*T)->rchild);
//判断高度差
if(rHeight - lHeight == 2)
{
if(data > (*T)->rchild->data)
{
//RR型
RRRotation(*T,T);
}
else
{
//RL型
LLRotation((*T)->rchild,&(*T)->rchild);
RRRotation(*T,T);
}
}
}
(*T)->height = Max(GetHeight((*T)->lchild),GetHeight((*T)->rchild)) + 1;
}
void Preorder(TreeNode *T)
{
if(T)
{
printf("%d",T->data);
Preorder(T->lchild);
Preorder(T->rchild);
}
}
int GetHeight(TreeNode *node)
{
return node ? node->height : 0;
}
void RRRotation(TreeNode *node,TreeNode **root)
{
TreeNode *temp = node->rchild;
node->rchild = temp->lchild;
temp->lchild = node;
node->height = Max(GetHeight(node->lchild),GetHeight(node->rchild)) + 1;
temp->height = Max(GetHeight(node->lchild),GetHeight(node->rchild)) + 1;
*root = temp;
}
void LLRotation(TreeNode *node,TreeNode **root)
{
TreeNode *temp = node->lchild;
node->lchild = temp->rchild;
temp->rchild = node;
node->height = Max(GetHeight(node->lchild),GetHeight(node->rchild)) + 1;
temp->height = Max(GetHeight(node->lchild),GetHeight(node->rchild)) + 1;
*root = temp;
}
int Max(int a,int b)
{
return a > b ?a : b;
}
测试结果:
声明:此文章为学习笔记,如有侵权请联系删除。