HuffmanTree的构建
HuffmanTree定义:
带权路径长度最小的二叉树WPL(Weighted Path Length )
即权值大的外结点离根节点最近的扩充二叉树
算法描述:
(1)根据给定的n个权值{w1,w2,w3,…,wn},构造具有n棵扩充二叉树的森林F={T1,T2,T3,…,Tn},其中每棵扩充二叉树Ti只有一个带权值wi的根结点,其左、右子树均为空。
(2)重复以下步骤,直到F中仅剩下一棵树为止:
①在F中选取两棵根结点权值最小的扩充二叉树,作为左、右子树构造一棵新的二叉树。置新的二叉树的根结点的权值为左、右子树根结点上的权值之和。
②在F中删去这两棵二叉树。
③把新的二叉树加入到F当中。
实现代码如下所示
HuffmanTree.h
ifndef HAFFMANTREE_H
define HAFFMANTREE_H
include “MinHeap.h”
include
include
using namespace std;
//Huffman树结点的类定义
template
endif
程序中引入一个最小堆,利用它组织森林并从中选择根结点权值最小和次小的两棵树
MinHeap.h
ifndef MINHEAP_H
define MINHEAP_H
include
include
using namespace std;
const int DefaultSize=50;
template
endif
下面是测试函数
由“data中的数据进行测试”
“data.txt”
26
713
173
341
360
1156
139
190
356
680
28
64
396
312
619
642
238
4
630
612
852
320
97
163
17
148
5
“测试所用代码”
include
include
include “HuffmanTree.h”
include “MinHeap.h”
using namespace std;
struct Huffmancode{//定义存储霍夫曼编码及相关信息的结构体
char c;//存储字符
int weight;//存储该字符的权重
string code;//存储该字符的Huffman编码
int length;//存储该字符的长度
};
int main(){
ifstream fin(“data.txt”);//读取每一个字符对应的权重
assert(fin);//断言文件打开成功且不为空
int n=26,i;
assert(fin >> n);
int * w = new int[n+1];
// cout << “There are ” << n << ” nodes in the file.\n”;
///测试函数,输出各个结点存储的元素值
// cout << “The weight of each node is:\n”;
for( i = 1; i <= n; i++){
fin >> w[i];//将各个结点的权值读写进入最小堆当中
// cout << “weight[” << i << “]: ” << w[i] << endl;
}
cout << “\nCreate huffman tree:\n”;
HuffmanTree