每次把权值最小的两颗二叉树合并
typedef struct TreeNode *HuffmanTree;
struct TreeNode{
int weight;
HuffmanTree left,right;
}
HuffmanTree Huffman(MinHeap H)
{
int i;HuffmanTree T;
BuildMinHeap(H)//将H->Element[]按权值调整为最小堆
for(i=0;i<H->size;i++){
T=malloc(sizeof(struct TreeNode));//建立新节点
T->left=DeleteMin(H);//从最小堆中删除一个节点,作为新T的左节点;
T->right=DeleteMin(H);//再删除一个节点作为新T的右节点
T->weight=T->left->weight+T->right->weight;
Insert(H,T);//将新T插入到最小堆
}
T=DeleteMin(H);
return T;
}
huffman树 的特点:
没有度为1的节点;
n个叶子节点的哈夫曼树一共有2n-1个节点;