HuffmanTree 改进

来源:互联网 发布:搞笑网络歌曲 编辑:程序博客网 时间:2024/05/22 03:27
#include <iostream>
using namespace std; 
struct Node
{
int weight;
int parent;
int Lchild;
int Rchild;
};
class HuffmanTree
{
private:
Node *node;
int Num;
public:
HuffmanTree(int n);
void Order();
void Print();
}; 
//creat the Huffman tree
HuffmanTree::HuffmanTree(int n)//n is the total leaves,then2n-1 is the total nodes
{
Num = n;
node = new Node[2*Num-1];
for (int k=0;k<2*Num -1;k++)
{
if (k<Num)
{
printf("please input every weight\n");
scanf("%d",&node[k].weight);
}
else
{
// isn't leaf
node[k].weight=0;
}
node[k].parent=node[k].Lchild=node[k].Rchild=0;
}
for (int l=Num;l <2*Num-1;l++)
{
int min1=32767;
int min2=32767;//store the two min value
int p1=0;
int p2=0;//store the index
for (int j=0;j<=l-1;j++)
{
if (node[j].parent==0)
{
if (node[j].weight<min1)
{
min2=min1;
p2=p1;
p1=j;
min1=node[j].weight;
}
else 
if (node[j].weight<min2)
{
min2=node[j].weight;
p2=j;
}
}
//please ensure the code's position
node[l].Lchild=p1;
node[l].Rchild=p2;
node[l].weight=min1+min2;
node[p1].parent=l;;
node[p2].parent=l;
}
void HuffmanTree::Order()
{
//bubbling way 
int flag;
int temp;
for (int i=0;i<Num-1;i++)
{
flag=1;
for (int j=0;j<Num-i-1;j++)
{
if (node[j].weight>node[j+1].weight)
{
temp=node[j].weight;
node[j].weight=node[j+1].weight;
node[j+1].weight=temp;
flag=0;
}
}
if (flag==1)
{
printf("the order is completed in the times of ");
printf("%d",i );//the order is completed
cout<<endl;
break;
}
}
return;
void HuffmanTree::Print()
{
for (int l=0;l<2*Num-1;l++)
cout<<node[l].weight<<endl;
return;
int main()
{
cout<<"please input the numberof leaves"<<endl;
int number;
cin>>number;
HuffmanTree test_tree_(number);
test_tree_.Order();
cout<<"the following is theresult"<<endl;
cout<<"from the bottom to thetop ,and from the left to theright"<<endl;
test_tree_.Print();
return 0;
}
原创粉丝点击