【数据结构】Huffman树
作者:互联网
关于代码的错误
关于哈夫曼树的构造函数老师给的代码和书上的原代码都有错误,我稍稍修改了一下。
代码如下
template <class T, class E>HuffmanTree<T,E>::HuffmanTree(E w[], int n){
//给出n个权值w[1]~w[n-1], 构造Huffman树
MinHeap<T, HuffmanNode<T,E> > hp; //使用最小堆存放森林的结点
HuffmanNode<T, E> *parent=NULL,fir_temp, sec_temp, tmp,*first,*second;
int i;
root = new HuffmanNode<T, E>[2*n - 1];
for (i = 0; i < n; i++)
{//按棵逐步建立森林中的树木,并作为Huffman树的叶结点。数据放入森林
tmp.data = w[i];
tmp.leftChild = NULL;
tmp.rightChild = NULL;
tmp.parent = NULL;
hp.Insert(tmp); //森林信息插入最小堆中
}
for (i = 0; i < n-1; i++){ //n-1趟, 建Huffman树
hp.RemoveMin(fir_temp); //根权值最小的树
first = new HuffmanNode<T,E>;
*first = fir_temp;//first指向对应的最小结点
hp.RemoveMin(sec_temp); //根权值次小的树
second = new HuffmanNode<T,E>;
*second = sec_temp;//second指向对应的次小结点
parent = new HuffmanNode<T, E>;
parent->leftChild = first;
parent->rightChild = second;
parent->data = first->data + second->data;
hp.Insert(*parent); //新结点插入堆中
}
root = new HuffmanNode<T,E>;//建立根结点
hp.RemoveMin(fir_temp);
*root = fir_temp;
//输出哈夫曼树中各个叶结点的哈夫曼编码
cout<<" root = "<<root->data<<endl;
output(root,string(),cout);
cout << endl;
buildCode(root, "");//输出各叶结点的哈夫曼编码
}
算法步骤
1)如果是叶结点将s赋值给它的haffmancode,输出,返回
2)递归左子树,得到左子树叶结点的哈夫曼编码
3)递归右子树,得到右子树叶结点的哈夫曼编码
void HuffmanTree<T, E>::buildCode(HuffmanNode<T, E> *x, string s)
{
//在这里添加你完成任务的代码
if (x->isLeaf()) //判断x是否为叶结点
{
x->haffmancode = s;
cout << x->data << " 的哈夫曼编码为:" << x->haffmancode << endl;
return;
}
else
{
buildCode(x->leftChild, s + '0');
buildCode(x->rightChild, s + '1');
}
}
运行结果
标签:tmp,结点,temp,parent,second,HuffmanNode,数据结构,Huffman 来源: https://www.cnblogs.com/muyefeiwu/p/11845173.html