哈夫曼树的建立
Posted marybubble
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了哈夫曼树的建立相关的知识,希望对你有一定的参考价值。
闲暇的夜晚, 写个哈夫曼树练练笔。
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<algorithm>
typedef struct
{
char data;
int w,parent, lchild, rchild;
int use;
}HFNode,*HuffmanTree;
char N[100]; //用以保存结点的data
int w[100]; //权值
typedef struct
{
int s1, s2;
}Mincode; //存储最小权值与次小权值结点的下标
int cmpw1(HuffmanTree HC,int q) //找出最小权值的结点的下标
{
int i,min = 666666,pos=0;
for (i = 0; i < q; i++)
{
if ((HC + i)->w < min&& (HC + i)->use==1)
{
min = (HC + i)->w;
pos = i;
}
}
return pos;
}
int cmpw2(HuffmanTree HC, int q,int s) //找出次小权值的结点的下标
{
int i, min = 666666, pos = 0;
for (i = 0; i < q; i++)
{
if ((HC + i)->w < min&&i!=s&& (HC + i)->use == 1)
{
min = (HC + i)->w;
pos = i;
}
}
return pos;
}
Mincode Select(HuffmanTree HC, int q)
{
Mincode code;
code.s1=cmpw1(HC, q);
code.s2 = cmpw2(HC, q, code.s1);
return code;
}
int main()
{
HuffmanTree HC;
Mincode code;
printf("Input N:\n");
scanf("%s",N);
int n = strlen(N);
int m = 2 * n - 1;
int i = 0;
HC = (HuffmanTree)malloc(m * sizeof(HFNode));
printf("Input W:\n");
for (int i = 0; i < n; i++)
scanf("%d",&w[i]);
for (i = 0; i < n; i++) //初始化
{
(HC + i)->data = N[i];
(HC + i)->w = w[i];
(HC + i)->parent = 0;
(HC + i)->lchild = 0;
(HC + i)->rchild = 0;
(HC + i)->use = 1;
}
for (; i < m; i++)
{
(HC + i)->data =‘0‘;
(HC + i)->w =0;
(HC + i)->parent = 0;
(HC + i)->lchild = 0;
(HC + i)->rchild = 0;
(HC + i)->use = 1;
}
for (int i = n; i < m; i++) //构造哈夫曼树
{
code=Select(HC, i);
printf("%d %d\n",code.s1,code.s2);
(HC + code.s1)->use = 0;
(HC + code.s2)->use = 0;
(HC + code.s1)->parent = i;
(HC + code.s2)->parent = i;
(HC + i)->lchild = code.s1;
(HC + i)->rchild = code.s2;
(HC + i)->w = (HC + code.s1)->w+(HC+code.s2)->w;
}
printf("data\tw\tparent\tlchild\trchild\n");
for (int i = 0; i < m; i++)
printf("%c\t%d\t%d\t%d\t%d\t\n",(HC+i)->data,(HC+i)->w,(HC+i)->parent,(HC+i)->lchild,(HC+i)->rchild);
return 0;
}
以上是关于哈夫曼树的建立的主要内容,如果未能解决你的问题,请参考以下文章