哈夫曼编码

本文介绍了一个使用C++实现的哈夫曼树构建及编码过程。文章详细展示了如何输入结点权重并构建哈夫曼树,接着通过遍历树来为每个字符分配哈夫曼编码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <string>
#define n 4
#define m 2*n-1
using namespace std;
const int MAX = 100;

typedef struct
{
    int weight;
    int parent, lchild, rchild;
} HuffmanTree;

typedef HuffmanTree hfmtree[m + 1];

typedef struct
{
    char  ch;
    char code[n + 1];
} CodeNode;

typedef CodeNode hfmcode[n + 1];
void CreateHuffmanTree(HuffmanTree tree[])
{
    int m1, m2;
    int l, r;
    for(int i = 1; i <= m; i++)
    {
        tree[i].weight = 0;
        tree[i].lchild = 0;
        tree[i].rchild = 0;
        tree[i].parent = 0;
    }
    cout << "请输入" << n << "个结点的权值:" << endl;
    for(i = 1; i <= n; i++)
    {
        cin >> tree[i].weight;
    }
    for(i = n + 1; i <= m; i++)
    {
        m1 = m2 = 32767;
        l = r = 0;
        for(int k = 1; k <= i - 1; k++)
            if(tree[k].parent == 0)
                if(tree[k].weight < m1)
                {
                    m2 = m1;
                    r = l;
                    m1 = tree[k].weight;
                    l = k;
                }
                else if(tree[k].weight < m2)
                {
                    m2 = tree[k].weight;
                    r = k;
                }
        tree[l].parent = i;
        tree[r].parent = i;
        tree[i].lchild = l;
        tree[i].rchild = r;
        tree[i].weight = tree[l].weight + tree[r].weight;
    }

}

void ShowHuffmanTree(HuffmanTree tree[])
{
    cout << "哈夫曼数的最终状态:" << endl;
    cout << "权值,双亲,左孩子,右孩子:" << endl;
    for(int i = 1; i <= m; i++)
        cout << tree[i].weight << "," << tree[i].parent << "," << tree[i].lchild << ","
             << tree[i].rchild << endl;
    cout << endl;
}

void HuffmanCoding(HuffmanTree tree[], CodeNode H[])
{
    int start, c, p;
    char cd[n + 1], chh;
    cd[n] = '\0';
    cout << "请输入各结点的字符:(" << "共" << n << "个)" << endl;
    for(int i = 1; i <= n; i++)
    {
        cin >> chh;
        H[i].ch = chh;
        start = n;
        c = i;
        while(p = tree[c].parent)
        {
            if(tree[p].lchild == c)
                cd[--start] = '0';
            else
                cd[--start] = '1';
            c = p;
        }
        strcpy(H[i].code, &cd[start]);
    }
    cout << endl;
    for(i = 1; i <= n; i++)
        cout << "第" << i << "个字符" << H[i].ch << "的编码为:" << H[i].code << endl;

}

void main()
{
    hfmtree t;
    hfmcode h;
    CreateHuffmanTree(t);
    HuffmanCoding(t, h);
    ShowHuffmanTree(t);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值