Huffman编码C实现
Huffman编码:根据Huffman树进行编码的,用到的数据结构是二叉树。
typedef int elemtype;
typedef struct
{
elemtype weight;
int parent,l_child,r_child;
} binarytree;
//2、构建最优二叉树
void CreateHuffman(int leafnum, binarytree *huffmantree)
{
//leafnum个叶子,决定nodenum个结点数
int nodenum=2*leafnum-1;
huffmantree=(binarytree *)malloc(nodenum*sizeof(binarytree)); //0号单元也使用
//leafnum个叶子,决定nodenum个结点数,也决定了(nodenum-1)个bit位编码
char *huffmancode;
huffmancode =(char *)malloc((nodenum-1)*sizeof(char));
//huffmantree的初始化:叶子结点data权值手动输入,非叶子默认值都为0
cout<<"请输入叶子权值:";
int i;
for(i=0;i>huffmantree[i].weight;
}
else
{
huffmantree[i].weight=0;
}
huffmantree[i].parent=huffmantree[i].l_child=huffmantree[i].r_child=0;
}
int j;
//j从leafnum开始,指的是包含了新建子树的结点编号
for(j=leafnum;j>leafnum;
CreateHuffman( leafnum, T);
while(1);
}
编译结果如下:

