平衡二叉树
来源:互联网 发布:网络免费打电话下载 编辑:程序博客网 时间:2024/04/29 20:42
前面已经讲过平衡二叉树的实现原理以及实例
原理参见 http://blog.csdn.net/wxbmelisky/article/details/47755753
实例参见 http://blog.csdn.net/wxbmelisky/article/details/47787963
平衡二叉树的实现代码如下
- #include <stdio.h>
- #include <stdlib.h>
-
- #define TRUE 1
- #define FALSE 0
-
-
- typedef struct BiTNode
- {
- int data;
- int bf;
- BiTNode *lchild, *rchild;
- }BiTNode, *BiTree;
-
- typedef int Status;
-
-
- void R_Rotate( BiTree *p )
- {
- BiTree L;
- L = (*p)->lchild;
- (*p)->lchild = L->rchild;
- L->rchild = *p;
- *p = L;
- }
-
-
- void L_Rotate( BiTree *p )
- {
- BiTree R;
- R = (*p)->rchild;
- (*p)->rchild = R->lchild;
- R->lchild = *p;
- *p = R;
- }
-
-
- void LeftBalance( BiTree *T )
- {
- BiTree L, Lr;
- L = (*T)->lchild;
- switch( L->bf )
- {
- case 1:
- (*T)->bf = L->bf = 0;
- R_Rotate( T );
- break;
- case -1:
- Lr = L->rchild;
- switch( Lr->bf )
- {
- case 1:
- (*T)->bf = -1;
- L->bf = 0;
- break;
- case 0:
- (*T)->bf = L->bf = 0;
- break;
- case -1:
- (*T)->bf = 0;
- L->bf = 1;
- break;
- }
- Lr->bf = 0;
- L_Rotate( &(*T)->lchild );
- R_Rotate( T );
- }
- }
-
-
- void RightBalance( BiTree *T )
- {
- BiTree R, Rl;
- R = (*T)->rchild;
- switch( R->bf )
- {
- case -1:
- (*T)->bf = R->bf = 0;
- L_Rotate( T );
- break;
- case 1:
- Rl = R->lchild;
- switch( Rl->bf )
- {
- case 1:
- (*T)->bf = 0;
- R->bf = -1;
- break;
- case 0:
- (*T)->bf = R->bf = 0;
- break;
- case -1:
- (*T)->bf = 1;
- R->bf = 0;
- break;
- }
- Rl->bf = 0;
- R_Rotate( &(*T)->rchild );
- L_Rotate( T );
- }
- }
-
-
-
-
-
- Status InsertAVL( BiTree *T, int e, Status *taller )
- {
- if( !*T )
- {
- *T = (BiTree)malloc(sizeof(BiTNode));
- (*T)->data = e;
- (*T)->lchild = (*T)->rchild = NULL;
- (*T)->bf = 0;
- *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 1:
- LeftBalance( T );
- *taller = FALSE;
- break;
- case 0:
- (*T)->bf = 1;
- *taller = TRUE;
- break;
- case -1:
- (*T)->bf = 0;
- *taller = FALSE;
- break;
- }
- }
- }
- else
- {
- if( !InsertAVL( &(*T)->rchlid, e, taller ) )
- {
- return FALSE;
- }
-
- if( *taller )
- {
- switch( (*T)->bf )
- {
- case 1:
- (*T)->bf = 0;
- *taller = FALSE;
- break;
- case 0:
- (*T)->bf = -1;
- *taller = TRUE;
- break;
- case -1:
- RightBalance( T );
- *taller = FALSE;
- break;
- }
- }
- }
- }
-
- return TRUE;
- }
-
-
- void CreateAVL()
- {
- int i;
- int a[10] = {2,1,0,3,4,5,6,9,8,7};
- BiTree T = NULL;
- Status taller;
-
- for( i=0; i<10; i++ )
- {
- InsertAVL( &T, a[i], &taller );
- }
- }