创建哈夫曼树
#include <iostream>
using namespace std;
struct Huffman
{
int weight;
int left;
int right;
};
struct miniHeap
{
int weight;
int index;
};
miniHeap Heap[1024];
Huffman Huff[1024];
int in_number[1024],n,id;
void Down(int i)
{
int t,flag = 0;
while(2*i <= n && flag == 0)
{
if(Heap[i*2].weight < Heap[i].weight)
t = i*2;
else
t = i;
if (i*2+1 <= n)
{
if(Heap[i*2+1].weight < Heap[t].weight)
t = i*2+1;
}
if(t != i)
{
swap(Heap[i], Heap[t]);
i = t;
}
else
flag = 1;
}
}
void up(Huffman number)
{
n++;
Heap[n].weight = number.weight;
Heap[n].index = id;
int flag = 0;
int m = n;
while(flag == 0 && m != 1)
{
if(Heap[m].weight < Heap[m/2].weight)
swap(Heap[m], Heap[m/2]);
else
flag = 1;
m = m/2;
}
}
void show()
{
// 显示结果
for(int i=1;i<id;i++)
cout << Huff[i].weight << "-" << Huff[i].left << "," << Huff[i].right << " ";
cout << endl << endl;
for(int i=1;i<=n;i++)
cout << Heap[i].weight << "-" << Heap[i].index << " ";
cout << endl;
}
int creatHuffmanTree()
{
cin >> n;
id = n;
for(int i=1;i<=n;i++)
{
cin >> Heap[i].weight;
Heap[i].index = i;
Huff[i].weight = Heap[i].weight;
Huff[i].left = Huff[i].right = 0;
}
for(int i=n/2;i>=1;i--)
Down(i);
while(n>=2)
{
// 取出第一个堆顶元素
miniHeap heap1 = Heap[1];
Heap[1] = Heap[n--];
Down(1);
// 取出第二个堆顶元素
miniHeap heap2 = Heap[1];
Heap[1] = Heap[n--];
Down(1);
// 生成新的哈夫曼节点
Huff[id].weight = heap1.weight+heap2.weight;
Huff[id].left = heap1.index;
Huff[id].right = heap2.index;
// 将新的哈夫曼节点插入最小堆中
up(Huff[id++]);
show();
}
return id;
}
int main()
{
// 7 19 21 2 3 6 7 10
creatHuffmanTree();
return 0;
}