// balanceTree.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include"BiTNode.h"
#define LH +1
#define EH 0
#define RH -1
#include<malloc.h>
using namespace std;
void LeftBalance(BiTree *T) //结点的bf大于0(左子树高度大于右子树)
{
BiTree L, Lr;
L = (*T)->lchild;
switch (L->bf)
{
case LH:
(*T)->bf = L->bf = EH;
R_Rotate(T);
break;
case RH:
Lr = L->rchild;
switch (Lr->bf)
{
case LH:
(*T)->bf = RH;
L->bf = EH;
break;
case EH:
(*T)->bf = L->bf = EH;
break;
case RH:
(*T)->bf = EH;
L->bf = LH;
break;
}
Lr->bf = EH;
L_Rotate(&(*T)->lchild); R_Rotate(T); } } void RightBalance(BiTree *T) //结点的bf小于0(右子树大于左子树高度) { BiTree R, Rr; R = (*T)->rchild;
switch (R->bf)
{
case RH:
(*T)->bf = R->bf = EH;
L_Rotate(T);
break;
case LH:
Rr = R->lchild;
switch (Rr->bf)
{
case LH:
(*T)->bf = EH;
R->bf = RH;
break;
case EH:
(*T)->bf = R->bf = EH;
break;
case RH:
(*T)->bf = LH;
R->bf = EH;
break;
}
Rr->bf = EH;
R_Rotate(&(*T)->rchild); L_Rotate(T); } } #define Status bool Status InsertAVL(BiTree *T, int e,Status *taller) { if (!*T) { *T = (BiTree)malloc(sizeof(BiTNode)); (*T)->data = e;
(*T)->lchild = (*T)->rchild = nullptr;
(*T)->bf = EH;
*taller = true;
}
else
{
if (e == (*T)->data) { *taller = false; return false; } if (e < (*T)->data) { if (!InsertAVL(&(*T)->lchild, e, taller)) return false; if (*taller) { switch ((*T)->bf) { case LH: LeftBalance(T); *taller = false; break; case EH: (*T)->bf = LH;
*taller = true;
break;
case RH:
(*T)->bf = EH;
*taller = false;
break;
}
}
}
else
{
if (!InsertAVL(&(*T)->rchild, e, taller)) return false; if (*taller) { switch ((*T)->bf) { case LH: (*T)->bf = EH;
*taller = false;
break;
case EH:
(*T)->bf = RH;
*taller = true;
break;
case RH:
RightBalance(T);
*taller = false;
break;
}
}
}
}
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
int i;
int a[10] = { 3, 2, 1, 4, 5, 6, 7, 10, 9, 8 };
BiTree T = nullptr;
bool taller;
for (i = 0; i < 10; i++)
{
InsertAVL(&T, a[i], &taller);
}
return 0;
}
大话数据结构(平衡二叉树)
原文作者:平衡二叉树
原文地址: https://blog.csdn.net/liugg2016/article/details/78522448
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/liugg2016/article/details/78522448
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。