`````` #include <iostream>
#include <string>
using namespace std;
//#define MaxValue 10000; //初始设定的权值最大值
//#define MaxBit 4; //初始设定的最大编码位数
//#define Max 20 //初始设定的最大结点个数
struct HaffNode //哈夫曼树的结点结构
{
string data;
int weight; //权值
int flag; //标记
int parent; //双亲结点下标
int leftChild; //左孩子下标
int rightChild; //右孩子下标
};
struct Code //存放哈夫曼编码的数据元素结构
{
int bit[]; //数组
int start; //编码的起始下标
int weight; //字符的权值
};

void Haffman( int n, HaffNode haffTree[])
//建立叶结点个数为n权值为weight的哈夫曼树haffTree
{
int j, m1, m2, x1, x2;
//哈夫曼树haffTree初始化。n个叶结点的哈夫曼树共有2n-1个结点
for(int i = 0; i < 2 * n - 1 ; i++)
{

haffTree[i].weight = 0;
haffTree[i].parent = 0;
haffTree[i].flag = 0;
haffTree[i].leftChild = -1;
haffTree[i].rightChild = -1;
}
//构造哈夫曼树haffTree的n-1个非叶结点
for(int i = 0;i < n-1;i++)
{
m1 = m2 = n;
x1 = x2 = 0;
for(j = 0; j < n+i;j++)//找出剩下的两个比较小的节点
{
if (haffTree[j].weight < m1 && haffTree[j].flag == 0)
{
m2 = m1;
x2 = x1;
m1 = haffTree[j].weight;
x1 = j;
}
else
if(haffTree[j].weight < m2 && haffTree[j].flag == 0)
{
m2 = haffTree[j].weight;
x2 = j;
}
}
//将找出的两棵权值最小的子树合并为一棵子树
haffTree[x1].parent = n+i;
haffTree[x2].parent = n+i;
haffTree[x1].flag = 1;
haffTree[x2].flag = 1;
haffTree[n+i].weight = haffTree[x1].weight+haffTree[x2].weight;
haffTree[n+i].leftChild = x1;
haffTree[n+i].rightChild = x2;
}
}
void dayin(HaffNode haffTree[],int k ,int n)
{
if(k==0)
{
return;
}
for (int i=0;i<n;i++)
{
cout<<" ";
}
if(haffTree[k].parent!=-1)
{
cout<<"|_";
}
else {
cout<<" ";
}
cout<<haffTree[k].data<<endl;
int L=haffTree[k].leftChild;
int R=haffTree[k].rightChild;
dayin(haffTree,R,n+2);
dayin(haffTree,L,n+2);
}

void HaffmanCode()
//由n个结点的哈夫曼树haffTree构造哈夫曼编码haffCode
{
int i,k,n;
HaffNode haffTree[2*n-1];
Code cd[2*n-1];
int child;
int parent;
//求n个叶结点的哈夫曼编码
for(int i = 0; i < n; i++)
{
cd->start = n-1; //不等长编码的最后一位为Max-1
cd->weight = haffTree[i].weight; //取得编码对应权值的字符
child=i;
parent = haffTree[child].parent;
//由叶结点向上直到根结点
while(parent != 0)
{
if(haffTree[parent].leftChild == child)
cd->bit[cd->start] = 0; //左孩子结点编码0
else
cd->bit[cd->start] = 1;//右孩子结点编码1
cd->start--;
child = parent;
parent = haffTree[child].parent;
}
}
Haffman( 0,  haffTree);
cout<<"输出哈夫曼码：";
for(i=1;i<=n;i++)
{
cout<<haffTree[i].data<<": ";
for(k=cd[i].start;k<=n;k++)
cout<<cd[i].bit[k];
cout<<endl;
}
for(i=0;i<2*n-1;i++)
{
if(haffTree[i].flag==0)
dayin(haffTree,2*n-1,0);
cout<<endl;
}
}
int main(int argc, char *argv[])
{
int i, j,n ;
cout<<"输入字符个数: ";
cin>>n;
string* s = new string[2*n-1];
int* w = new int[2*n-1];
for(i=0;i<n;i++)
{
cout<<"请输入字符：";
cin>>s[i];
cout<<"请输入权值: ";
cin>>w[i];
}
return 0;
}

``````

5个回答

Haffman(对应的权值,对对应的具体的hafftree数组)，

Hafftree1为哈夫曼数组

sirxiangsir 为什么显示错误，haffTree没有被声明啊？？？

sirxiangsir 我想要在运行界面自己定义要输入的权值的话，该怎么写？？？

HaffNode haffTree[] 定义一个这样的数组

sirxiangsir 我把代码贴给你，你能不能教我一下怎么弄？

class1.函数名(参数列表)