Huffman树做了好久,就是打印不出来他的编码,我感觉和别人的一样啊,好奇怪,求指导
//jianfeng Hu,2016.11.10
//哈夫曼树
#include<iostream>
#include<string>
using namespace std;
typedef struct
{
int weight;
int parent, lch, rch;
}HTNode, *HuffmanTree;
typedef char **HuffmanCode;
void Select(HuffmanTree HT, int yu, int *s1, int *s2)
{
int sl1 = 0, sl2 = 0;
for (int i = 1; i <= yu; i++)
{
if (HT[i].parent == 0)
{
if (sl1 == 0)
sl1 = i;
else if (sl2 == 0)
sl2 = i;
else
{
if ((HT[i].weight < HT[sl2].weight) || (HT[i].weight < HT[sl1].weight))
{
if (HT[sl1].weight > HT[sl2].weight)
sl1 = i;
else
sl2 = i;
}
}
}
}
*s2 = (sl1 > sl2 ? sl1 : sl2);
*s1 = (sl1 < sl2 ? sl1 : sl2);
}
void CreatHuffmanTree(HuffmanTree &HT, int n)
{
if (n <= 1)
return;
int m = 2 * n - 1;
HT = new HTNode[m + 1];
for (int i = 1; i <= m; i++)
{
HT[i].lch = 0;
HT[i].rch = 0;
HT[i].parent = 0;
}
cout << "请依次输入每一个字符的权值:";//输入
for (int i = 1; i <= n; ++i)
{
cin >> HT[i].weight;
}
//构造
int s1, s2;
for (int i = n + 1; i <= m; ++i)
{
Select(HT, i - 1, &s1, &s2);
HT[s1].parent = i;
HT[s2].parent = i;
HT[i].lch = s1;
HT[i].rch = s2;
HT[i].weight = HT[s1].weight + HT[s2].weight;
}
//输出验证
cout << "i\tweight\tparent\tlc\trc" << endl;
for (int i = 1; i <= m; i++)
{
cout << i << "\t" << HT[i].weight << "\t" << HT[i].parent << "\t" << HT[i].lch << "\t" << HT[i].rch << endl;
}
}
void CreatHuffmanCode(HuffmanTree HT, HuffmanCode &HC, int n)
{
int start, c, f;
char *cd = new char[n];
HC = new char*[n + 1];
cd[n - 1] = '\0';
cout << "每个字符的哈夫曼编码:" << endl;
for (int i = 1; i <= n; ++i)
{
start = n - 1;
c = i;
f = HT[i].parent;
while (f != 0)
{
--start;
if (HT[f].lch == c)
cd[start] = '0';
else
cd[start] = '1';
c = f;
f = HT[f].parent;
}
HC[i] = new char[n - start];
strcpy(HC[i], &cd[start]);
cout << HC[i] << " ";
}
delete cd;
}
void main()
{
int n;
HuffmanTree HT = NULL;
HuffmanCode HC;
cout << "请输入结点的个数:";
cin >> n;
CreatHuffmanTree(HT, n);
CreatHuffmanCode(HT, HC, n);
}来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4571/viewspace-3139453/ ,如需转载,请注明出处,否则将追究法律责任。