哈夫曼树
struct treenode
{
int weight;
struct treenode *left, *right;
};
struct treenode *huffman(minheap h)
{ //假设h->size个权值已经存在h->elements[]->weight里
int i;
struct treenode *t;
buildminheap(h); //将h->elements[]按权值调整为最小堆
for(i = 0; i < h->size ; i++) //做h->size-1次合并
{
t = (struct treenode *)malloc(sizeof(struct treenode)); //建立新节点
t->left = deletemin(minheap); //从最小堆中删除一个结点,作为新t的左子节点
t->right = deletemin(minheap); //从最小堆中删除一个结点,作为新t的右子结点
t->weight = t->right->weight + t->left->weight; //计算新权值
insert(h,t); //将新t插入最小堆
}
t = deletemin(h);
return t;
}
哈夫曼编码
minheap h = create(n); //创建一个空的最小堆
h = readdata(n); //将f[]读入h->data中
struct treenode *t = huffman(h); //创建一个huffman树
int codelen = wpl(t , 0); //计算最优编码长度
int wpl(struct treenode *t,int depth)
{
if(!t->left && !t->right)
{
return depth * t->weight;
}
else //否则一定有两个孩子
{
return(wpl(t->left,depth + 1) + wpl(t->right,depth + 1));
}
}