创建哈佛曼树并求出哈弗曼编码

#include<stdio.h>
#include<string.h> 
#include<iostream>
#include<algorithm>
using namespace std;

struct hTNode{
 unsigned int weight;
 unsigned int parent,lchild,rchild;
};

typedef hTNode* huffTree;
//定义一个双重指针来存放Huffman编码
typedef char** huffCode;
//树上所有结点的个数
int cnt,i;

/**
 * 选择权值最小的两个结点
 * tree: 哈弗曼树
 * n: 哈弗曼树上结点的个数
 * s1,s2: 选出来的结果 ,即在树上的位置
*/
void select(huffTree tree, int n, int &s1, int &s2)
{
 int i;
 for(i = 2; i <= n; i ++)
 {
  if(tree[s1].parent != 0)
  {
   s1 = i;
   continue;
  }
  if(tree[i].parent == 0)
   if(tree[i].weight < tree[s1].weight)
    s1 = i ;
 }
 for(i = 1; i <= n; i ++)
 {
  if(i == s1) continue;
  if(s2 == s1 || tree[s2].parent != 0)
  {
   s2 = i;
   continue;
  }
  if(tree[i].parent == 0)
   if(s1 != s2 && tree[i].weight < tree[s2].weight)
    s2 = i ;
 }
}

/**
 * 这个函数是本程序的最主要的函数,用来建立哈弗曼树,同时生成哈弗曼编码。
 * n: 输入的数据的个数
 * weight: 每个节点的权值
 * tree: 哈弗曼树
 * code: 哈弗曼编码
*/
void HuffEncoding(int n, int* weight, huffTree &tree, huffCode &codes)
{
 int s1=1, s2=2;
 huffTree p;
 //如果输入的数据个数小于2,那么直接返回
 if(n < 2) return;
 cnt = 2*n - 1;

 //申请这棵哈弗曼树的内存空间
 tree = (huffTree)malloc((cnt+1)*sizeof(hTNode));
 //把每一个录入的数据建成结点(或者说小树)
 for(p = tree+1,i = 1; i <= n; ++i, ++p, ++weight)
 {
  p->weight = *weight; 
  p->lchild = 0;
  p->rchild = 0;
  p->parent = 0;
 }
 //初始化哈弗曼树上的每一个结点,先都设成0
 for(;i <= cnt; ++i, ++p) 
 {
  p->weight = 0;
  p->lchild = 0;
  p->rchild = 0;
  p->parent = 0;
 }
 //开始建立哈弗曼树
 for(i = n + 1; i <= cnt; ++ i)
 {
  select(tree, i-1, s1, s2);
  tree[s1].parent = i;
  tree[s2].parent = i;
  tree[i].lchild = s1;
  tree[i].rchild = s2;
  tree[i].weight = tree[s1].weight + tree[s2].weight;
 }
 //开始求各个叶子结点的Huffman编码
 {
  char* cd;
  int start,c,f=0;
  codes = (huffCode)malloc((n+1)*sizeof(char*));
  cd = (char*)malloc((n+1)*sizeof(char));
  cd[n-1]='/0';
  for(i = 1; i <= n; ++i)
  {
   start = n - 1;
   for(c = i,f = tree[i].parent; f != 0; 
   c = f, f = tree[f].parent)
    if(tree[f].lchild == c) cd[--start] = '0';
    else cd[--start] = '1';
   codes[i] = (char*)malloc((n - start)*sizeof(char));
   strcpy(codes[i],&cd[start]);
  }
  free(cd);
 }

}//HuffEncoding

int main()
{
 int nn;
 int* weight;
 huffTree tree; 
 huffCode codes;
 printf("请输入结点的个数:");
 scanf("%d",&nn);
 printf("\n");
 weight = (int*)malloc(nn*sizeof(int));
 printf("请输入各个结点的权值:");
 for(i = 0; i < nn; i ++)
 {
  scanf("%d",&weight[i]);
 }
  printf("\n");
 HuffEncoding(nn,weight,tree,codes);
 printf("各个结点的哈弗曼编码如下:\n");
   printf("\n");
 for(i = 1; i <= nn; i ++)
 {
  printf("结点%d的哈弗曼编码为:%s\n",tree[i].weight,codes[i]);
    printf("\n");
 }
 return 0;
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值