数据结构与算法分析-AVL树的实现

 #ifndef _AVL_TREE_H #define _AVL_TREE_H struct AvlNode; typedef struct AvlNode *Position; typedef struct AvlNode *AvlTree; AvlTree MakeEmpty( AvlTree T ); Position Find( int X, AvlTree T ); Position FindMin( AvlTree T ); Position FindMax( AvlTree T ); AvlTree Insert( int X, AvlTree T ); AvlTree Delete( int X, AvlTree T ); #endif

 

#include <stdio.h> #include <malloc.h> #include <assert.h> #include "avltree.h" struct AvlNode { int Element; AvlTree Left; AvlTree Right; int Height; }; int Max( int a, int b) { if( a > b ) return a; else return b; } static int Height( Position P ) { if ( P == NULL ) return -1; else return P->Height; } Position SingleRotateWithLeft( Position k2 ) { Position k1; k1 = k2->Left; k2->Left = k1->Right; k1->Right = k2; k2->Height = Max( Height( k2->Left ), Height( k2->Right ) ) + 1; k1->Height = Max( Height( k1->Left ), Height( k1->Right ) ) + 1; return k1; } Position SingleRotateWithRight( Position k2 ) { Position k1; k1 = k2->Right; k2->Right = k1->Left; k1->Left = k2; k2->Height = Max( Height( k2->Left ), Height( k2->Right ) ) + 1; k1->Height = Max( Height( k1->Left ), Height( k1->Right ) ) + 1; return k1; } Position DoubleRotateWithLeft( Position k3 ) { k3->Left = SingleRotateWithRight( k3->Left ); return SingleRotateWithLeft( k3 ); } Position DoubleRotateWithRight( Position k3 ) { k3->Left = SingleRotateWithLeft( k3->Right ); return SingleRotateWithRight( k3 ); } AvlTree Insert( int X, AvlTree T ) { if ( T == NULL ) { T = malloc( sizeof(struct AvlNode) ); assert( T != NULL ); T->Element = X; T->Height = 0; T->Left = T->Right = NULL; } else if ( X < T->Element ) { T->Left = Insert( X, T->Left ); if ( Height(T->Left) - Height(T->Right) == 2 ) if ( X < T->Left->Element ) T = SingleRotateWithLeft( T ); else T = DoubleRotateWithLeft( T ); } else if ( X > T->Element ) { T->Right = Insert( X, T->Right ); if ( Height( T->Right ) - Height( T->Left ) == 2 ) if ( X > T->Right->Element ) T = SingleRotateWithRight( T ); else T = DoubleRotateWithRight( T ); } T->Height = Max( Height( T->Left ), Height( T->Right ) ) + 1; return T; } void PrintTree( AvlTree T ) { if ( T != NULL ) { printf("--%d--/n--|--/n", T->Element ); if ( T->Left != NULL ) { printf("--LEFT--/n"); PrintTree( T->Left ); } if ( T->Right != NULL ) { printf("--RIGHT--/n"); PrintTree( T->Right ); } } } int main(int argc, char** argv) { AvlTree tree = NULL; tree = Insert( 7, tree ); tree = Insert( 4, tree ); tree = Insert( 11, tree ); tree = Insert( 3, tree ); tree = Insert( 8, tree ); tree = Insert( 14, tree ); // PrintTree( tree ); tree = Insert( 2, tree ); // PrintTree( tree ); tree = Insert( 12, tree ); tree = Insert( 13, tree ); PrintTree( tree ); return 0; }

你可能感兴趣的:(数据结构与算法分析-AVL树的实现)