哈夫曼树的构建和编码实现

数据结构(第二版) 严蔚敏

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
#define inf 9999999
int n,m;
typedef char **huffmancode;
typedef struct
{
    int weigth;
    int parent, lchild, rchild;
}htnode, *huffmantree;

void Select(huffmantree &ht,int s,int &s1,int &s2)
{
    s1=s2=0;
    int min1,min2;
    min1=min2=inf;
    for(int j=1;j<=s;j++) 
    if(ht[j].parent==0)  
    {
        if(ht[j].weigth<=min1)
        {
        min2=min1;
        min1=ht[j].weigth;
         s2=s1;s1=j;
        }
        else if(ht[j].weigth<=min2)
        {
            min2=ht[j].weigth;
            s2=j;
        }
    }      
}

void createhuffmantree(huffmantree &ht, int n)
{
    if (n <= 1) return;
     m = 2 * n - 1;
    ht = new htnode[m + 1];
    for (int i = 1; i <= m; ++i)
    {
        ht[i].parent = 0; ht[i].lchild = 0; ht[i].rchild = 0;
    }
    for (int i = 1; i <= n; i++) cin >> ht[i].weigth;
    for (int i = n + 1; i <= m; i++)
    {
        int s1,s2;
        Select(ht,i-1,s1,s2);
        ht[s1].parent = i; ht[s2].parent = i;
        ht[i].lchild = s1; ht[i].rchild = s2;
        ht[i].weigth = ht[s1].weigth+ ht[s2].weigth;
    }
}

void createhuffmancode(huffmantree &ht,huffmancode &hc,int n)
{
    hc=new char*[n+1];
    char *cd=new char[n];
    for(int i=1;i<=n;i++)
    {
        int start=n-1,c=i,f=ht[i].parent;
        while(f!=0)
        {
            --start;
            if(ht[f].lchild==c) cd[start]='0';
            else cd[start]='l';
            c=f;f=ht[f].parent;
        }
        hc[i]=new char[n-start];strcpy(hc[i],&cd[start]);
    }delete cd;
}

int main()
{ 
    cout<<"请输入叶子结点数目(n>1):"<<endl;
    cin>>n;
    cout<<"请输入权值"<<endl; 
    huffmantree ht;
    huffmancode hc;
    createhuffmantree(ht,n); 
    for(int i=1;i<=m;i++)
    {
        cout<<ht[i].weigth<<' ';
    }
    cout<<endl; 
    createhuffmancode(ht,hc,n);
    for(int i=1;i<=n;i++)
    {
        cout<<ht[i].weigth<<' '<<hc[i]<<endl;
    }
    delete ht; 
}

 

转载于:https://www.cnblogs.com/siuh/p/8976637.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值