代码如下:
#include <iostream>
using namespace std;
int s1, s2;typedef struct {int weight;int parent, lch, rch;
} HTNode, *HuffmanTree;void Select(HuffmanTree &HT, int n, int &s1, int &s2) {int minv;//定义一个临时变量存储最小值for (int i = 1; i <= n; i++) { //开始找第一个最小值if (HT[i].parent == 0) {minv = i;break;}}for (int i = 1; i <= n; i++) {if (HT[i].parent == 0)if (HT[i].weight < HT[minv].weight)minv = i;}s1 = minv;//开始找第二个最小值,且与第一个不同for (int i = 1; i <= n; i++) {if (HT[i].parent == 0 && i != s1) {minv = i;break;}}for (int i = 1; i <= n; i++) {if (HT[i].parent == 0 && i != s1)if (HT[i].weight < HT[minv].weight)minv = i;}s2 = minv;
}void CreatHuffmanTree(HuffmanTree HT, int n) {if (n <= 1)return ;int m = 2 * n - 1; //数组共2n-1个元素HT = new HTNode[m + 1]; //0号单元未用,HT[m]表示根节点for (int i = 1; i <= m; i++) {HT[i].lch = 0;//初始化HT[i].rch = 0;HT[i].parent = 0;}for (int i = 1; i <= n; i++) {cin >> HT[i].weight; //输入前n个元素的weight值}//初始化结束,下面开始建立哈夫曼树for (int i = n + 1; i <= m; i++) { //合并产生n-1个结点-构造哈夫曼树Select(HT, i - 1, s1, s2); //在HT[k](1<=k<=i-1)中选择两个其双亲域为0,//且权重最小的结点,并返回它们在HT中的序号s1和s2HT[s1].parent = i;//表示从F中删除s1,s2HT[s2].parent = i;HT[i].lch = s1;//s1,s2分别作为i的左右孩子HT[i].rch = s2;HT[i].weight = HT[s1].weight + HT[s2].weight;//i的权重为左右孩子权重之和cout << HT[i].weight << " " << "(" << HT[s1].weight << "," << HT[s2].weight << ")" << endl;}
}int main() {HuffmanTree H;int n;cin >> n;CreatHuffmanTree(H, n);return 0;
}
测试结果: