通过写这个编码和huffman树的构建,让我对huffman tree 有了更深的理解:
1:首先huffman是经过n-1次迭代之后生成的树,所以如果开始的节点有n个的话,那麽生成之后的的树的节点个数是2*n-1
2:编码的话可以用DFS处理;
3:树的节点新加了一个parents值,让我学到了一种新的写法。//在挑选最小值的时候需要
#include<iostream>
#include <iomanip>
#include <algorithm>
#include <string>
#include <map>
using namespace std;
struct element
{
char c=NULL;
int weight; // 权值域
int lchild, rchild, parent; // 该结点的左、右、双亲结点在数组中的下标
string code;
};
// 选取权值最小的两个结点
void selectMin(element a[],int n, int &s1, int &s2)
{ int i,j;
for ( i = 0; i < n; i++)
{
if (a[i].parent == -1)// 初始化s1,s1的双亲为-1
{
s1 = i;
break;
}
}
for (; i < n; i++)// s1为权值最小的下标
{
if (a[i].parent == -1 && a[s1].weight > a[i].weight)