平衡二叉树介绍 C语言实现
作者:互联网
网上看了一些平衡二叉树的说明和实现,自己再实现一遍加深记忆
typedef struct TAG_AVL_T{
int data; // value
int factor; // 平衡因子
int hight; //二叉树高度
BT_NODE* left; //左
BT_NODE* right;
}BT_NODE;
#define LH +1 //代表节点拥左子树
#define EH 0 //代表节点同时(不)拥有左右子树
#define RH -1 //代表节点拥有右子树
BT_NODE tree=NULL; //全局变局记录根节点
//左旋转
BT_NODE LRotate(BT_NODE *tree){
BT_NODE *tmp; //tree A
tmp = tree->right; //tmp C
tree->right = tmp->left; //A节点的右子树从C指向F(C的左子树)
tmp->left = tree; //C的左子树指向原根节点A
tree = tmp; //指针指向C节点
return tmp;
}
//右旋转
BT_NODE* RRotate(BT_NODE tree){
BT_NODE tmp; //tree A
tmp = tree->left; //tmp 指向B
tree->left = tmp->right; //A的左子树从B指向E
tmp->right = tree; //B的右子树从E指向A
tree = tmp; //栈顶指针指向B
return tmp;
}
插入数据后,可能导致二叉数不平衡,就要进行平衡。这时候就会调用左旋和右旋
插入数据
void* createNode(int data){
BT_NODE* T;
T = malloc(sizeof(BT_NODE));
T->data = data;
T->left = T->right = NULL;
T->factor = EH;
T->height = 0;
return T;
}
void LeftBalance(BT_NODE* T){
BT_NODE *left , *left_right;
left = T->left;
left_right = left->right;
switch(left->factor){
case LH : //父子节点都为LH,要进行右旋进行平衡
RRotate(T);
left->factor = EH;//右旋右了树被填充,这个节点满了
T->factor = EH;// T节点空的左右子树都为空了
break;
case EH:
break;
case RH://子节点下面又插入了右子树
//如果为RH,L要先进行左旋转,使T->lchild->bf和T->bf一致
switch(left_right ->factor){
case EH :
//先进行左旋转后,再进行右旋转。T和left都没有子树了
T->factor = left->factor = EH;
break;
case LH:
//进行左右旋转后,T为空节点。left 有右子树
T->factor = EH;
left->factor = RH;
break;
case RH:
//进行左右旋转后,T有左子树。left为空
left->factor = EH;
T->factor = LH;
break;
}
left_right ->bf = EH;//无论什么情况,left_right 的左右子树都会被填满
LRotate(left);
RRotate(T);
break;
}
}
void RightBalance(BT_NODE* T){
BT_NODE *right, *right_left;
right = T->right;
right_left= right ->left;
switch(right->factor){
cast RH:
//进行右旋后R节点满,而T节点为空
T->factor = right->factor = EH;
break;
case EH:
break;
case LH:
switch(right_left->factor ){
case EH:
T->factor = right->factor = EH;
break;
case LH:
right->factor = EH;
T->factor =RH;
break;
case RH:
T->factor = EH;
right->factor =LH;
break;
}
right_left->bf = EH;
RRotate(right );
LRotate(T);
}
}
void BTBalance(BT_NODE* T , int insert_type , bool *taller){
*taller = false;
if(insert_type == 1){ //左插入成功
switch(T->factor){
case EH
标签:right,EH,C语言,BT,二叉树,factor,平衡,节点,left 来源: https://blog.csdn.net/bruk_spp/article/details/97135051