实验5 哈夫曼树

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define MAXNUM 60

typedef struct
{
	int weight;
	int parent;
	int lchild;
	int rchild;
}HTNode,*huffmantree;

void Select(huffmantree HT, int g, int &s1, int &s2);

//输入叶子的权值,并输出所有的权值
void creattree(huffmantree &HF,int n)
{
    int i,m;
    if(n<=1) return;
    m=2*n-1;
    HF=(huffmantree)malloc((m+1)*sizeof(HTNode));
    for(i=1;i<=m;++i)
    {
        HF[i].parent=0;
        HF[i].lchild=0;
        HF[i].rchild=0;
    }
    printf("输入叶子权值\n");
    for(i=1;i<=n;++i)
    {
       scanf("%d",&HF[i].weight);
    }
     for(i=n+1;i<=m;++i)
     {
         int g,s1,s2;
         Select(HF,i-1,s1,s2);
           HF[s1].parent=i;
           HF[s2].parent=i;
           HF[i].lchild=s1;
           HF[i].rchild=s2;
           HF[i].weight=HF[s1].weight+HF[s2].weight;
     }
     printf("输出权值\n");
     for(i=1;i<=m;i++)
     printf("%d  ",HF[i].weight);
     printf("\n");
}
//Select函数找两个最小值
void Select(huffmantree HT, int g, int &s1, int &s2)
    {
       int j, k, m, n;
       for(k=1; k<=g; k++)
       {
          if(HT[k].parent==0)
          {
            s1=k;
            break;
           }
       }

       for(j=1; j<=g; j++)
       {
          if((HT[j].weight<=HT[k].weight)&&(HT[j].parent==0))

          s1=j;
       }

       for(m=1; m<=g; m++)
       {
          if((HT[m].parent==0)&&(m!=s1))
          {
            s2=m;
            break;
           }
       }

       for(n=1; n<=g; n++)
       {
         if((HT[n].weight<HT[m].weight)&&(HT[n].parent==0)&&(n!=s1))
           s2=n;
       }
   }

int  main()
 {
	 int n;
     huffmantree HF;
     printf("输入叶子个数\n");
     scanf("%d",&n);
     creattree(HF,n);
 }

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值