给定n个权值作为n个叶子结点,构造一棵二叉树,若该树的带权路径长度达到最小,称这样的二叉树为最优二叉树,也称为哈夫曼树。由此得到的二进制前缀编码称为哈夫曼编码。
例如权w={5,29,7,8,14,23,3,11},8个结点,构造的哈夫曼树如下图所示:
算法实现如下:
typedef struct {
unsigned int weight;
unsigned int parent;
unsigned int lchild;
unsigned int rchild;
}Node, *HuffmanTree;
typedef char **HuffmanCode;
//在huffmanTree[1...n-1]中选择parent为0,且weight最小的两个结点,分别是s1,s2
void Select(HuffmanTree& huffmanTree, int n,int &s1,int &s2)
{
int min = 1;
for(int i =1;i<=n;i++){
if(huffmanTree[i].parent==0){
min = i;
break;
}
}
for(int i =1;i<=n;i++){
if(huffmanTree[i].parent==0){
if(huffmanTree[i].weight<huffmanTree[min].weight){