bitree_init(init,free);
if((data = (HuffNode*)malloc(sizeof(HuffNode))) == NULL)
{
pqueue_destroy(&pqueue);
return -1;
}
data->symbol = c;
data->freq = freqs[c];
if(bitree_ins_left(init,NULL,data) != 0)
{
free(data);
bitree_destroy(init);
free(init);
pqueue_destroy(&pqueue);
return -1;
}
/*将二叉树插入优先队列*/
if(pqueue_insert(&pqueue,init) != 0)
{
bitree_destroy(init);
free(init);
pqueue_destroy(&pqueue);
return -1;
}
}
}
/*通过两两合并优先队列中的二叉树来构建霍夫曼树*/
for(c=1; c<=size-1; c++)
{
/*为合并后的树分配空间*/
if((merge = (BiTree *)malloc(sizeof(BiTree))) == NULL)
{
pqueue_destroy(&pqueue);
return -1;
}
/*提取队列中拥有最小频率的两棵树*/
if(pqueue_extract(&pqueue,(void **)&left) != 0)
{
pqueue_destroy(&pqueue);
free(merge);
return -1;
}
if(pqueue_extract(&pqueue,(void **)right) !=0)
{
pqueue_destroy(&pqueue);
free(merge);
return -1;
}
/*分配新产生霍夫曼结点的空间*/
if((data = (HuffNode *)malloc(sizeof(HuffNode))) == NULL)
{
pqueue_destroy(&pqueue);
free(merge);
return -1;
}
memset(data,0,sizeof(HuffNode));
/*求和前面提取的两棵树的频率*/
data->freq = ((HuffNode *)bitree_data(bitree_root(left)))->freq +
((HuffNode *)bitree_data(bitree_root(right)))->freq;
/*合并left、right两棵树*/
if(bitree_merge(merge,left,right,data) != 0)
{
pqueue_destroy(&pqueue);
free(merge);
return -1;
}
/*把合并后的树插入到优先级队列中,并释放left、right棵树*/
if(pqueue_insert(&pqueue,merge) != 0)
{
pqueue_destroy(&pqueue);
bitree_destroy(merge);
free(merge);
return -1;
}
free(left);
free(right);
}