HuffmanTree 改进

#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,then 2n-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 number of leaves"<<endl;
int number;
cin>>number;
HuffmanTree test_tree_(number);
test_tree_.Order();
cout<<"the following is the result"<<endl;
cout<<"from the bottom to the top ,and from the left to the right"<<endl;
test_tree_.Print();
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值