#include<iostream>
using namespace std;
struct huff
{
int weight;
huff *left,*right;
};
int *coding = new int[10];
class huffmantree
{
huff *Tree;
public:
huffmantree();
huff *get();
void init();
void show( huff *tree );
int weightlen( huff *tree,int len );
void huffcoding( huff *tree,int len );
};
huffmantree::huffmantree()
{
Tree = NULL;
}
huff *huffmantree::get()
{
return Tree;
}
//建立huffmantree
void huffmantree::init()
{
int n,i,j;
cout << "Input the n: \n";
cin >> n;
int *a = new int[n];
cout << "Input the numbers:\n";
for( i=0;i<n;i++ ) //读入权值
{
cin >> a[i];
}
huff **b = new huff*[n];
huff *q;
for( i=0;i<n;i++ ) //建立结构体数组,让其一一对应
{
b[i] = new huff;
b[i]->weight = a[i];
b[i]->left = NULL;
b[i]->right = NULL;
}
for( i=1;i<n;i++ ) //建立huffmantree
{
int k1 = -1,k2;
for( j=0;j<n;j++ )
{
if( b[j] != NULL && k1 == -1 ) //k1 k2指向头两个
{
k1 = j;
continue;
}
if( b[j] != NULL )
{
k2 = j;
break;
}
}
for( j=k2;j<n;j++ ) //k1指向最小 k2指向次小
{
if( b[j] != NULL )
{
if( b[j]->weight < b[k1]->weight )
{
k2 = k1;
k1 = j;
}
else if( b[j]->weight < b[k2]->weight )
{
k2 = j;
}
}
}
//由权值最小和次小的建立一棵树,q指向树根节点
q = new huff;
q->weight = b[k1]->weight + b[k2]->weight;
q->left = b[k1];
q->right = b[k2];
b[k1] = q;
b[k2] = NULL;
}
delete [] b;
Tree = q;
q= NULL;
cout << "建立成功\n";
}
//求带权路径长度
int huffmantree::weightlen( huff *tree,int len )
{
if( tree == NULL )
{
return 0;
}
else
{
if( tree->left == NULL && tree->right == NULL )
return tree->weight * len;
else
{
return weightlen( tree->left,len+1 )+weightlen( tree->right,len+1 );
}
}
}
//huffman编码
void huffmantree::huffcoding( huff *tree,int len )
{
if( tree != NULL )
{
if( tree->left == NULL && tree->right == NULL )
{
int i;
cout << "节点权值为" << tree->weight << "的编码为:";
for( i=0;i<len;i++ )
{
cout << coding[i];
}
cout << endl;
}
else
{
coding[len] = 0;
huffcoding( tree->left,len+1 );
coding[len] = 1;
huffcoding( tree->right,len+1 );
}
}
}
//先序遍历huffmantree
void huffmantree::show( huff *tree )
{
if( tree != NULL )
{
cout << tree->weight << ' ';
show( tree->left );
show( tree->right );
}
}
int main()
{
huffmantree tree;
int choose;
cout << "\t1.建立huffmantree\n"
<< "\t2.先序遍历输出\n"
<< "\t3.huaffman编码\n"
<< "\t4.求带权路径长度\n"
<< "\t0退出\n";
while( 1 )
{
cin >> choose;
if( choose == 0 )
break;
switch( choose )
{
case 1:
{
tree.init();
cout << endl;
break;
}
case 2:
{
tree.show( tree.get() );
cout << endl;
break;
}
case 3:
{
int len = 0;
tree.huffcoding( tree.get(),len );
cout << endl;
break;
}
case 4:
{
int len = 0;
len = tree.weightlen( tree.get(),len );
cout << len << endl;
break;
}
}
}
delete [] coding;
return 0;
}