平衡二叉树的插入调整实现.
#include <iostream>
#include <queue>
using namespace std;
typedef int ElementType;
typedef struct AVLNode* Position;
typedef Position AVLTree;
struct AVLNode{
ElementType Data;
AVLTree Left, Right;
int Height;
} ;
int Max ( int a, int b) {
return a> b? a: b;
}
int GetHeight ( AVLTree T) {
if ( ! T) return - 1 ;
return T-> Height;
}
AVLTree SingleLeftRotation ( AVLTree A) {
AVLTree B= A-> Left;
A-> Left= B-> Right;
B-> Right= A;
A-> Height= Max ( GetHeight ( A-> Left) , GetHeight ( A-> Right) ) + 1 ;
B-> Height= Max ( GetHeight ( B-> Left) , A-> Height) + 1 ;
return B;
}
AVLTree SingleRightRotation ( AVLTree A) {
AVLTree B= A-> Right;
A-> Right= B-> Left;
B-> Left= A;
A-> Height= Max ( GetHeight ( A-> Left) , GetHeight ( A-> Right) ) + 1 ;
B-> Height= Max ( GetHeight ( B-> Left) , A-> Height) + 1 ;
return B;
}
AVLTree DoubleLeftRightRotation ( AVLTree A) {
A-> Left= SingleRightRotation ( A-> Left) ;
return SingleLeftRotation ( A) ;
}
AVLTree DoubleRightLeftRotation ( AVLTree A) {
A-> Right= SingleLeftRotation ( A-> Right) ;
return SingleRightRotation ( A) ;
}
AVLTree Insert ( AVLTree T, ElementType X) {
if ( ! T) {
T= ( AVLTree) malloc ( sizeof ( AVLNode) ) ;
T-> Data= X;
T-> Height= 0 ;
T-> Left= T-> Right= NULL ;
return T;
}
else if ( X< T-> Data) {
T-> Left= Insert ( T-> Left, X) ;
if ( GetHeight ( T-> Left) - GetHeight ( T-> Right) == 2 ) {
if ( X< T-> Left-> Data)
T= SingleLeftRotation ( T) ;
else
T= DoubleLeftRightRotation ( T) ;
}
} else if ( X> T-> Data) {
T-> Right= Insert ( T-> Right, X) ;
if ( GetHeight ( T-> Left) - GetHeight ( T-> Right) == - 2 ) {
if ( X> T-> Right-> Data)
T= SingleRightRotation ( T) ;
else
T= DoubleRightLeftRotation ( T) ;
}
}
T-> Height= Max ( GetHeight ( T-> Left) , GetHeight ( T-> Right) ) + 1 ;
return T;
}
void LevelOrderTraversal ( AVLTree BT) {
queue< AVLTree> Q; AVLTree T;
if ( ! BT) return ;
Q. push ( BT) ;
while ( ! Q. empty ( ) ) {
T= Q. front ( ) ;
printf ( "%5d" , T-> Data) ;
Q. pop ( ) ;
if ( T-> Left) Q. push ( T-> Left) ;
if ( T-> Right) Q. push ( T-> Right) ;
}
}
int main ( ) {
AVLTree T= NULL ;
T= Insert ( T, 8 ) ;
T= Insert ( T, 9 ) ;
T= Insert ( T, 7 ) ;
T= Insert ( T, 2 ) ;
T= Insert ( T, 3 ) ;
T= Insert ( T, 5 ) ;
T= Insert ( T, 6 ) ;
T= Insert ( T, 4 ) ;
LevelOrderTraversal ( T) ;
return 0 ;
}