数据结构--赫夫曼树及其应用

讲解请参考 赫夫曼

------ 赫夫曼树和赫夫曼编码的存储表示------

typedef struct {
    unsigned int weight;
    unsigned int parent,lchild,rchild;
}HTNode,*HuffmanTree;
typedef char ** HuffmanCode;
 
void HuffmanCoding(HuffmanTree& HT,HuffmanCode & HC,int *w,int n)  {
 
    if (n < 1) return;\
    int m = 2* n + 1;
    HT = (HuffmanTree) malloc (m+1)* sizeof(HTNode); //0 号单元未用
    for ( HuffmanTree p = HT; i=1; i<=n; ++i; ++p; ++w)  
        *p = {*w,0,0,0,0};
    for(; i<=m; ++i; ++p)
        *p = {0,0,0,0};
 
    for(i = n+1; i<=m; i++) {  //建立HuffmanTree
 
        Select(HT,i-1,s1,s2);
        HT[s1].parent = i; 
        HT[s2].parent = i; 
        HT[i].lchild = s1;
        HT[i].rchild = s2;
        HT[i].weight = HT[s1].weight + HT[s2].weight;
    }
 
    HC = (HuffmanCode)malloc((n+1)* sizeof(char*));
    cd = (char*) malloc(n* sizeof(char));
    cd [n-1] = "\0";
    for ( i=1; i<=n; i++) {
        int start = n-1;
        for ( c=i, f = HT[i].parent; f!=0; c=f; f = HT[f].parent )
            if( HT[f].lchild == c )  cd [--start] = "0";
            else cd [--start] = "1";
        HC[i] = (char*) malloc ( (n-start)* sizeof(char)); 
        strcyp(HC[i],&cd[start]);
    }
    free(cd);
 
}

------ 无栈非递归遍历赫夫曼树,求赫夫曼编码------

HC = (HuffmanCode) malloc ( (n+1) * sizeof(char*)); 
int p = m, cdlen = 0;

for ( int i=1; i<=m; ++i)  HT[i].weight = 0;

while(p) {

    if ( HT[p].weight == 0 ) {

        HT[p].weight = 1; 
        if ( HT[p].lchild != 0) {
            p = HT[p].lchild; 
            cd[cdlen++] = "0";
        }else if ( HT[p].lchild == 0) {

            HC[p] = (char*) malloc ((cdlen+1) * sizeof(char));
            cd[cdlen] = "\0"; 
            strcpy(HC[p],cd);
        }
    }else if ( HP[p].weight == 1) {

        HT[p].weight = 2;
        if ( HT[p].rchild != 0) {
            p = HT[p].rchild;
            cd [cdlen++] = "1";
        }else {
            HT[p].weight = 0; p = HT[p].parent; --cdlen;
        }
    }    
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

callinglove

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值