欢迎使用优快云-markdown编辑器

本文详细介绍了哈夫曼树的建立过程及其在数据编码中的应用,通过实例展示了如何构建哈夫曼树并为不同字符分配最优编码。

我的第一篇博客
哈夫曼树的建立与编码

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int n;
int m;
struct tree
{
    int weight;
    int parent;
    int Lchild;
    int Rchild;
}ht[];
struct coder
{
    int data;
    char code[10];
}hc[];
void select(struct tree ht[],int k,int *s1,int *s2)
{   
    int i;
    for(i=1; i<=k ; ++i)
    { 
        if(ht[i].parent == 0) 
            break;
    }  
    *s1 = i;  

    for(i=1; i<=k; ++i)
    {  
        if(ht[i].parent==0 && ht[i].weight<ht[*s1].weight)  
            *s1 = i;  
    }  

    for(i=1; i<=k; ++i)
    {  
        if(ht[i].parent==0 && i!=*s1)  
            break;  
    }  
    *s2 = i;  

    for(i=1; i<=k; ++i)
    {  
        if(ht[i].parent==0 && i!=*s1 && ht[i].weight<ht[*s2].weight)  
            *s2 = i;  
    }   
}
creat()
{
    struct tree *ht;
    struct coder *hc;
    int i,j,s1,s2,start,c,p;
    char *cd;
    ht=(struct tree*)malloc((n+1)*sizeof(struct tree)); 
    hc=(struct coder*)malloc((n+1)*sizeof(struct coder));
    cd=(char *)malloc(m*sizeof(char));
    cd[n-1]='\0';
    //建树
    for(i=1;i<=m;i++)
    {
        printf("请输入数字:");
        scanf("%d",&j);
        ht[i].weight =j;
        ht[i].parent =0;
        ht[i].Lchild =0;
        ht[i].Rchild =0;
    }
    for(i=m+1;i<n+1;i++)
    {
        ht[i].weight =0;
        ht[i].parent =0;
        ht[i].Lchild =0;
        ht[i].Rchild =0;
    }
    for(i=m+1;i<n+1;i++)
    {
        select(ht,i-1,&s1,&s2);
        ht[i].weight =ht[s1].weight +ht[s2].weight ;
        ht[i].Lchild =s1;
        ht[i].Rchild =s2;
        ht[s1].parent =i;
        ht[s2].parent =i;
    }
    for(i=1;i<n+1;i++)
        printf("%2d. %3d  %3d  %3d  %3d  \n",i,ht[i].weight ,ht[i].parent ,ht[i].Lchild ,ht[i].Rchild) ;
    //编码
    for(i=1;i<=m;i++)
    {
        start=n-1;
        c=i;
        p=ht[i].parent;
        while(p!=0)
        {
            --start;
            if(ht[p].Lchild ==c)
                cd[start]='0';
            else
                cd[start]='1';
            c=p;
            p=ht[p].parent ;
        }
        strcpy(hc[i].code,&cd[start]);
    }
    for(i=1;i<=m;i++)
        printf("%d--%s\n",ht[i].weight ,hc[i].code );
}
main()
{
    printf("节点数:");
    scanf("%d",&m);
    n=2*m-1;
    creat(n,m);
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值