目录
1.哈夫曼树的基本概念
2.哈夫曼树的构造算法
1.构造哈夫曼树的口诀
3.哈夫曼树构造算法的实现
1.结点类型定义
代码示例:
typedef struct{
int weight;
int parent,lch,rch;
}htnode,*huffmantree;
2.哈夫曼树构造算法的实现
代码示例:
void createhuffmantree(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;
}
for(int i = 1; i <= n; i++)
{
cin >> ht[i].weight;
}
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;
}
}
4.哈夫曼编码
1.哈夫曼编码的概念
2.哈夫曼编码的算法实现
代码示例:
void createhuffmancode(huffmantree ht,huffmancode &hc,int n)
{
hc = new char[n + 1];
char *cd;
cd = new char[n];
cd[n - 1] = '\0';
for(int i = 1; i <= n; i++)
{
int start = n - 1;
int c = i;
int 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]);
}
delete cd;
}
3.文件的编码与解码——应用举例
5.总的代码
typedef struct{
int weight;
int parent,lch,rch;
}htnode,*huffmantree;
void createhuffmantree(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;
}
for(int i = 1; i <= n; i++)
{
cin >> ht[i].weight;
}
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;
}
}
void createhuffmancode(huffmantree ht,huffmancode &hc,int n)
{
hc = new char[n + 1];
char *cd;
cd = new char[n];
cd[n - 1] = '\0';
for(int i = 1; i <= n; i++)
{
int start = n - 1;
int c = i;
int 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]);
}
delete cd;
}