平衡二叉树模板

poj2418字典树

#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
typedef struct AVLTree
{
    char name[31];
    int cnt;
    struct AVLTree *pLeft;
    struct AVLTree *pRight;
    int nHeight;
}AVLTree;
int n=0;
int Height(AVLTree * pNode)
{
    if(pNode==NULL) return -1;
    return pNode->nHeight;
}
AVLTree * LLRotate(AVLTree *pNode)
{
    AVLTree *pNode1;
    pNode1=pNode->pLeft;
    pNode->pLeft = pNode1->pRight;
    pNode1->pRight=pNode;

    pNode->nHeight=max(Height(pNode->pLeft),Height(pNode->pRight))+1;
    pNode1->nHeight=max(Height(pNode1->pLeft),pNode->nHeight)+1;

    return pNode1;
}
AVLTree *RRRotate(AVLTree * pNode)
{
    AVLTree *pNode1;
    pNode1=pNode->pRight;
    pNode->pRight=pNode1->pLeft;
    pNode1->pLeft=pNode;

    pNode->nHeight=max(Height(pNode->pLeft),Height(pNode->pRight))+1;
    pNode1->nHeight=max(pNode->nHeight,Height(pNode1->pRight))+1;
    return pNode1;
}

AVLTree * RLRotate(AVLTree * pNode)
{
    pNode->pRight =LLRotate(pNode->pRight);
    return RRRotate(pNode);
}
AVLTree *LRRotate(AVLTree *pNode)
{
    pNode->pLeft=RRRotate(pNode->pLeft);
    return LLRotate(pNode);
}
AVLTree * _Insert(char *s,AVLTree *pNode)
{
    if(pNode==NULL)
    {
        pNode =(AVLTree *) malloc(sizeof (AVLTree));
        strcpy(pNode->name,s);
        pNode->pLeft=pNode->pRight =NULL;
        pNode->cnt=1;
        pNode->nHeight =0;
    }
    else if(strcmp(pNode->name,s)<0)
    {
        pNode->pRight=_Insert(s,pNode->pRight);
        if(Height(pNode->pRight)-Height(pNode->pLeft)==2)
        {
            if(strcmp(s,pNode->name)>0)
                pNode=RRRotate(pNode);
            else pNode =RLRotate(pNode);
        }
    }
    else if(strcmp(pNode->name,s)>0)
    {
        pNode->pLeft=_Insert(s,pNode->pLeft);
        if(Height(pNode->pLeft)-Height(pNode->pRight)==2)
        {
            if(strcmp(s,pNode->name)>0)
                pNode=LRRotate(pNode);
            else pNode=LLRotate(pNode);
        }
    }
    else pNode->cnt++;
    pNode->nHeight=max(Height(pNode->pLeft),Height(pNode->pRight))+1;
    return pNode;
}
void mid_cal(AVLTree * pRoot)
{
    if(pRoot!=NULL)
    {
        mid_cal(pRoot->pLeft);
        printf("%s %.4f\n",pRoot->name,100.0*pRoot->cnt/n);
        mid_cal(pRoot->pRight);
    }
}

int main()
{
    AVLTree *pRoot=NULL;
    char s[31];
    while(gets(s)!=NULL)
    {
      //  puts("---------------------------");
        //if(strcmp(s,"null")==0) break;
        pRoot=_Insert(s,pRoot);
        n++;

    } mid_cal(pRoot);
   // printf("%d\n",n);

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值