哈夫曼树 源代码

来源:互联网 发布:淘宝拍a发b那个平台好 编辑:程序博客网 时间:2024/05/23 00:09

#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;

}