数据结构实验 哈夫曼树

构造一颗哈夫曼树,并且输出每个点的哈夫曼编码:

#include<iostream>
#include<cstring>
using namespace std;
typedef struct{
    int weight;
    int pre,lchild,rchild;
}*huffuman,hunode;
typedef char **huffumancode;//指向指针的指针 
#define inf 0x3f3f3f
int n,m;
void select(huffuman &HT,int n,int &s1,int &s2)//找出未访问过的点中权值最小的两个点 
{
    int min1=inf,min2=inf;
    s1=0,s2=0;            //s1 s2是用来记录下标 
    for(int i=1;i<=n;i++)
    {
        if(!HT[i].pre)
        {
            if(HT[i].weight<min1)
            {
                min2=min1;
                min1=HT[i].weight;
                s2=s1;
                s1=i;
            }
            else if(HT[i].weight<min2)
            {
                min2=HT[i].weight;
                s2=i;
            }
        }
    }
}
void creat_huffuman(huffuman &HT,int n)
{
    int m=2*n-1;
    HT=new hunode[m+1];
    for(int i=1;i<=m;i++)
    {
        HT[i].pre=0;
        HT[i].lchild=0;
        HT[i].rchild=0;
    }
    for(int i=1;i<=n;i++)
    cin>>HT[i].weight;
//*************************************************初始化 
    for(int i=n+1;i<=m;i++)
    {
        int s1,s2;
        select(HT,i-1,s1,s2);
        HT[s1].pre=i;
        HT[s2].pre=i;
        HT[i].weight=HT[s1].weight+HT[s2].weight;
        HT[i].lchild=s1;
        HT[i].rchild=s2;
    }
}
void creathuffumancode(huffuman &HT,huffumancode &HC,int n)
{//左0右1 
//从叶子节点向上遍历,直到根节点,同时把字符存进cd数组里 
    HC=new char*[n+1]; //HC是指针数组的首地址 
    char *cd=new char[n];
    cd[n-1]='';
    for(int i=1;i<=n;i++)
    {
        int start=n-1;
        int c=i;
        int f=HT[i].pre;;
        while(f)
        {
            --start;
            if(HT[f].lchild==c)
            cd[start]='0';
            else
            cd[start]='1';
            c=f;
            f=HT[f].pre;
        }
        HC[i]=new char[n-start];
        strcpy(HC[i],&cd[start]);//把字符复制到HC[i]里 
    }
}
void delete_huffuman(huffuman &HT,huffumancode &HC)
{
    delete[] HT;
    delete[] HC;
}
int main()
{
    cout<<"输入节点个数:"<<endl;
    cin>>n;
    cout<<"输入每个点的权值:"<<endl;
    huffuman HT=NULL;
    creat_huffuman(HT,n);
    for(int i=1;i<=2*n-1;i++)
    cout<<HT[i].weight<<' ';
    cout<<endl;
    huffumancode HC=NULL;
    creathuffumancode(HT,HC,n);
    for(int i=1;i<=n;i++)
    cout<<HT[i].weight<<':'<<HC[i]<<endl;
    delete_huffuman(HT,HC);
    return 0;
 } 
原文地址:https://www.cnblogs.com/6262369sss/p/9145360.html