#include<stdio.h>
#include<stdlib.h>
typedef struct AVLNode* Position;
typedef Position AVLTree;
struct AVLNode
{
int data;
AVLTree left,right;
int Height;
};
int Max(int a,int b)
{
if(a>=b)
return a;
if(b>a)
return b;
}
AVLTree Find(int x,AVLTree A)
{
if(x<A->data)
A=A->left;
else if(x>A->data)
A=A->right;
else
return A;
}
int GetHeight(AVLTree A)
{
int i,j;
i=j=0;
if(A->left!=NULL)
{
printf("left");
i=GetHeight(A->left);
i++;
}
if(A->right!=NULL)
{
j=GetHeight(A->right);
j++;
printf("right");
}
i=Max(i,j);
printf("%d",i);
return i;
}
AVLTree insert(int x,AVLTree A)
{
if(!A)
{
A=(AVLTree)malloc(sizeof(AVLNode));
A->data=x;
A->left=A->right=NULL;
}
else if(x<A->data)
{
A->left=insert(x,A->left);
if(GetHeight(A->left)-GetHeight(A->right)==2)
{
if(x<A->left->data)
A=SingleleftRotation(A);
else if(x>A->left->data)
A=DoubleleftrightRotation(A);
}
}
else if(x>A->data)
{
A->right=insert(x,A->right);
if(GetHeight(A->left)-GetHeight(A->right)==-2)
{
if(x<A->left->data)
A=SingleleftRotation(A);
else if(x>A->right->data)
A=DoublerightleftRotation(A);
}
}
A->Height=Max(GetHeight(A->left),GetHeight(A->right))+1;
return A;
}
int main()
{
AVLTree A=NULL,B=NULL;
int x,y;
printf("please input a number");
scanf("%d",&x);
while(x!=0)
{
A=insert(x,A);
printf("please input a number");
scanf("%d",&x);
}
scanf("%d",&x);
while(x!=0)
{
B=A;
A=Find(x,A);
y=GetHeight(A);
printf("树的高度为%d\n",y);
scanf("%d",&x);
A=B;
}
}
