哈夫曼树 源代码

#include<iostream>

#include<iomanip>

#include<string>

using namespace std;

typedef struct node

{

       int weight;

       int parent;

       int lchild;

       int rchild;

}H_node,*H_tree;

void print(H_tree t,int n)

{

       int i;

       for(i=0;i<2*n-1;++i)

       {

              cout<<setw(3)<<t[i].weight<<setw(3)<<t[i].parent<<setw(3)<<t[i].lchild<<setw(3)

                     <<t[i].rchild<<endl;

       }

}

void create(H_tree&t,int *p,int n)

{

       t=new H_node[2*n-1];

       int i;

       for(i=0;i<2*n-1;++i)

       {

              t[i].parent=0;

              if(i<n)

                     t[i].weight=p[i];

              else t[i].weight=0;

              t[i].lchild=0;

              t[i].rchild=0;

       }

}

void Find_min(H_tree t,int&min1,int&min2,int n)

{

       int i;

       int x1,x2;x1=x2=100000000;

       for(i=0;i<n;++i)

       {

              if(t[i].parent==0&&x1>t[i].weight)

              {

                     x2=x1; min2=min1;

                     x1=t[i].weight;

                     min1=i;

              }

              else

                     if(t[i].parent==0&&x2>t[i].weight)

                     {

                            x2=t[i].weight;

                            min2=i;

                     }

       }

}

void Hufmantree(H_tree&t,int n)

{

       int i,min1,min2;

       for(i=n;i<2*n-1;++i)

       {

              Find_min(t,min1,min2,i);

              t[i].weight=t[min1].weight+t[min2].weight;

              t[min1].parent=i;t[min2].parent=i;

              t[i].lchild=min1;t[i].rchild=min2;         

       }

}

void Print_H_tree(H_tree t,int n)

{

       int i,k,j;int h;

       cout<<"哈弗曼编码如下/n";

       for(i=0;i<n;++i)

       {

              string s;

              h=0;

              k=i;

              cout<<t[i].weight<<"   ";

       while(t[k].parent!=0)

       {

              j=t[k].parent;

              if(t[j].lchild ==k)s.insert(h,"0");

              else s.insert(h,"1");

              k=j;

              h++;

       }

       for(string::iterator i=s.end()-1;i>=s.begin();i--)

              cout<<*i;

      

       cout<<endl;

       }

}

int main()

{

       int  p[]={7,9,2,6};int n=4;//n为叶子节点个数

      

       H_tree t=NULL;

       create(t,p,n);Hufmantree(t,n);print(t,n);

       Print_H_tree(t,n);

       return 0;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值