C++实现哈夫曼编码

1.原理

1.哈夫曼树: 首先一串代权重的字符,从中选出2个权重最小的节点,组成一个父节点, 再从里面(除去两个最小的节点, 但包括那个父节点)选出最小的节点组成一个父节点,重复此步骤,直到找到最大权重的父节点(包括所有最初节点之和),就形成了一颗哈夫曼树。
2.哈夫曼编码: 根据哈夫曼树,左节点编码为0,右节点编码为1,就组成了哈夫曼编码。

2.源码实现

#include 
#include 
#include 
#include 

using namespace std;

#define MAXBIT 100
#define MAXVALUE 10000
#define MAXLEAF 30
#define MAXNODE MAXLEAF*2-1

typedef struct {
        double weight;
        int parent;
        int lchild;
        int rchild;
        char value;
} HNodeType;

typedef struct {
        int bit[MAXBIT];
        int start;
} HCodeType;

HNodeType HuffNode[MAXNODE];
HCodeType HuffCode[MAXLEAF];

/*构造哈夫曼树*/
void HuffmanTree(HNodeType *HuffNode, int n)
{
        double m1, m2;
        int x1, x2;
        int i, j;

        /*初始化哈夫曼数组中的节点*/
        for(i=0; i<2*n-1; i++)
        {
                HuffNode[i].weight = 0.0;
                HuffNode[i].parent = -1;
                HuffNode[i].lchild = -1;
                HuffNode[i].rchild = -1;
        }

        /*输入n个子节点的权值*/
        for(i=0; i> HuffNode[i].value >> HuffNode[i].weight;
        }

        /*构造哈夫曼树*/
        for(i=0; i> n;

        HuffmanTree(HuffNode, n);
        HuffmanCode(HuffCode, n);

        for(i=0; i

3.编译

$ g++ -o example example.cpp

4.运行及其结果

$ ./example
Please input n: 
6
Please input value and weight of leaf node 1
a 0.05
Please input value and weight of leaf node 2
b 0.32
Please input value and weight of leaf node 3
c 0.18
Please input value and weight of leaf node 4
d 0.07
Please input value and weight of leaf node 5
e 0.25
Please input value and weight of leaf node 6
f 0.13
a: Huffman code is: 1000
b: Huffman code is: 11
c: Huffman code is: 00
d: Huffman code is: 1001
e: Huffman code is: 01
f: Huffman code is: 101

你可能感兴趣的:(C++实现哈夫曼编码)