#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
struct AVL_tree_node
{
char name[31];
int cnt,height;
AVL_tree_node *pleft;
AVL_tree_node *pright;
};
int n=0;
int Height(AVL_tree_node *p)
{
if(p==NULL) return -1;
return p->height;
}
AVL_tree_node* LLRotate(AVL_tree_node *Root)
{
AVL_tree_node *p=Root->pleft;
Root->pleft=p->pright;
p->pright=Root;
Root->height=max(Height(Root->pleft),Height(Root->pright))+1;
p->height=max(Height(p->pleft),Root->height)+1;
return p;
}
AVL_tree_node* RRRotate(AVL_tree_node *Root)
{
AVL_tree_node *p=Root->pright;
Root->pright=p->pleft;
p->pleft=Root;
Root->height=max(Height(Root->pleft),Height(Root->pright))+1;
p->height=max(Height(p->pright),Root->height)+1;
return p;
}
AVL_tree_node* LRRotate(AVL_tree_node *Root)
{
Root->pleft=RRRotate(Root->pleft);
return LLRotate(Root);
}
AVL_tree_node* RLRotate(AVL_tree_node *Root)
{
Root->pright=LLRotate(Root->pright);
return RRRotate(Root);
}
AVL_tree_node* Insert(char s[],AVL_tree_node *Root)
{
if(Root==NULL)
{
Root=new AVL_tree_node;
strcpy(Root->name,s);
Root->cnt=1;
Root->height=0;
Root->pleft=Root->pright=NULL;
return Root;
}
int t=strcmp(s,Root->name);
if(t==0)
{
Root->cnt++;
}
else if(t<0)
{
Root->pleft=Insert(s,Root->pleft);
if(Height(Root->pleft)-Height(Root->pright)==2)
{
if(strcmp(s,Root->pleft->name)<0) Root=LLRotate(Root);
else Root=LRRotate(Root);
}
}
else
{
Root->pright=Insert(s,Root->pright);
if(Height(Root->pright)-Height(Root->pleft)==2)
{
if(strcmp(s,Root->pright->name)>0) Root=RRRotate(Root);
else Root=RLRotate(Root);
}
}
Root->height=max(Height(Root->pleft),Height(Root->pright))+1;
return Root;
}
void mid_cal(AVL_tree_node *Root)
{
if(Root!=NULL)
{
mid_cal(Root->pleft);
printf("%s %.4lf\n",Root->name,Root->cnt*100.0/n);
mid_cal(Root->pright);
}
}
int main()
{
AVL_tree_node *Root=NULL;
char s[31];
while(gets(s)!=NULL)
{
Root=Insert(s,Root);
n++;
}
mid_cal(Root);
}
AVL树模版
原文作者:AVL树
原文地址: https://blog.csdn.net/sinat_33397705/article/details/52445290
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/sinat_33397705/article/details/52445290
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。