#include<stdio.h>
#include<stdlib.h>
#include<time.h>
struct AVLNode{
int Data;
int Height;
struct AVLNode *Left;
struct AVLNode *Right;
};
int getHeight(struct AVLNode *T){
if(T==NULL){
return 0;
}
return T->Height;
}
int Max(int n1,int n2){
if(n1>n2){
return n1;
}
return n2;
}
struct AVLNode *SingleLeftRotation(struct AVLNode *AVLT){
struct AVLNode *temp;
temp=AVLT->Left;
AVLT->Left=temp->Right;
temp->Right=AVLT;
AVLT->Height=1+Max(getHeight(AVLT->Left),getHeight(AVLT->Right));
temp->Height=1+Max(getHeight(temp->Left),AVLT->Height);
return temp;
}
struct AVLNode *SingleRightRotation(struct AVLNode *AVLT){
struct AVLNode *temp;
temp=AVLT->Right;
AVLT->Right=temp->Left;
temp->Left=AVLT;
AVLT->Height=1+Max(getHeight(AVLT->Left),getHeight(AVLT->Right));
temp->Height=1+Max(AVLT->Height,getHeight(temp->Right));
return temp;
}
struct AVLNode *DoubleLeftRotation(struct AVLNode *AVLT){
AVLT->Left=SingleRightRotation(AVLT->Left);
return SingleLeftRotation(AVLT);
}
struct AVLNode *DoubleRightRotation(struct AVLNode *AVLT){
AVLT->Right=SingleLeftRotation(AVLT->Right);
return SingleRightRotation(AVLT);
}
struct AVLNode *AVLinsert(struct AVLNode *AVLT,int num){
if(AVLT==NULL){
AVLT=(struct AVLNode *)malloc(sizeof(struct AVLNode));
AVLT->Data=num;
AVLT->Height=1;
AVLT->Left=NULL;
AVLT->Right=NULL;
}else if(AVLT->Data>num){
AVLT->Left=AVLinsert(AVLT->Left,num);
if(getHeight(AVLT->Left)-getHeight(AVLT->Right)==2){
if(AVLT->Left->Data>num){
AVLT=SingleLeftRotation(AVLT);
}else{
AVLT=DoubleLeftRotation(AVLT);
}
}
}else if(AVLT->Data<num){
AVLT->Right=AVLinsert(AVLT->Right,num);
if(getHeight(AVLT->Right)-getHeight(AVLT->Left)==2){
if(AVLT->Right->Data<num){
AVLT=SingleRightRotation(AVLT);
}else{
AVLT=DoubleRightRotation(AVLT);
}
}
}
AVLT->Height=1+Max(getHeight(AVLT->Left),getHeight(AVLT->Right));
return AVLT;
}
int Count(struct AVLNode *T){
if(T==NULL){
return 0;
}
return 1+Count(T->Left)+Count(T->Right);
}
struct AVLNode *SqTinsert(struct AVLNode *T,int num){
if(T==NULL){
T=(struct AVLNode *)malloc(sizeof(struct AVLNode));
T->Data=num;
T->Height=1;
T->Left=NULL;
T->Right=NULL;
}else if(T->Data>num){
T->Left=SqTinsert(T->Left,num);
}else if(T->Data<num){
T->Right=SqTinsert(T->Right,num);
}
T->Height=Max(getHeight(T->Left),getHeight(T->Right));
return T;
}
int ASLCount(struct AVLNode*T){/*求ASL总数*/
if(T==NULL){
return 0;
}/*对于每一个第N层的节点通过递归总共会被数N次*/
return Count(T)+ASLCount(T->Left)+ASLCount(T->Right);
}
int main(){
struct AVLNode *AVLT=NULL;
struct AVLNode *SqT=NULL;
srand(time(NULL));
for(int i=1;i<1000200;i++){
int num=(rand()<<15)|rand();
AVLT=AVLinsert(AVLT,num);
SqT=SqTinsert(SqT,num);
}
printf("\nAVL树节点总数=%d\n",Count(AVLT));
printf("AVL树所有节点所在层次总和=%d\n",ASLCount(AVLT));
printf("AVL树平均ASL=%lf\n",(double)ASLCount(AVLT)/Count(AVLT));
printf("\n顺序二叉树节点总数=%d\n",Count(SqT));
printf("顺序二叉树所有节点所在层次总和=%d\n",ASLCount(SqT));
printf("顺序二叉树平均ASL=%lf",(double)ASLCount(SqT)/Count(SqT));
return 0;
}