哈夫曼树及编码

2130人阅读 评论(2)

/*在VC++里要删去getch()涵数和clrscr()涵数，可能是不支持吧！*/
/*win-tc*/
#include"stdio.h"
#include"stdlib.h"
#include"conio.h"
#include"malloc.h"
#define Num 20
typedef struct huffmanNode  /*定义结点*/
{
int weight;
int parent;
int lchild;
int rchild;
}huffmanNode;
huffmanNode huffmanTree[2*Num-1];
char* huffmanCode[Num];

void HuffmanCoding(int n);
void Select(int n,int* s1,int* s2);
void CreateHuffmanTree(int data[],int len);
void main()
{
int i;
int index=0;
int value;
int nodelist[Num];
clrscr();            /*清屏涵数*/
printf("/nplease input the elements of binary tree(Exit for 0):/n/n");
index=0;
scanf("%d",&value);
while(value!=0)         /*输入叶子的权值，以0结束*/
{
nodelist[index]=value;
index++;
scanf("%d",&value);
}
CreateHuffmanTree(nodelist,index);
HuffmanCoding(index);
for(i=0;i<index;i++)
{
printf("/n%3d: [",huffmanTree[i].weight);
printf("%s",huffmanCode[i]);
printf("]");
}
getch();         /**/
}

void Select(int n,int* s1,int* s2)
{
int i;
if(n<2)
return;
for(i=0;i<n;i++)
{
if(huffmanTree[i].parent==0)
{
*s1=i;
break;
}
for(i=0;i<n;i++) /*选出第一个权值最小的结点*/
{
if(huffmanTree[*s1].weight>huffmanTree[i].weight)
*s1=i;
}
}
for(i=0;i<n;i++)
{
if((huffmanTree[i].parent==0)&&(*s1!=i))
{
*s2=i;
break;
}
}
for(i=0;i<n;i++)  /*选出第二个权值最小的结点*/
{
if((huffmanTree[i].parent==0)&&(*s1!=i))
{
if(huffmanTree[*s2].weight>huffmanTree[i].weight)
*s2=i;
}
}
}

/*创建*/
void CreateHuffmanTree(int data[],int len)
{
int i;
int m;
int s1=0,s2=0;
m=2*len-1;
for(i=0;i<len;i++)
{
huffmanTree[i].weight=data[i];
}
for(i=len;i<m;i++)
{
Select(i,&s1,&s2);
huffmanTree[s1].parent=i;  /*置父结点*/
huffmanTree[s2].parent=i;
huffmanTree[i].lchild=s1; /*生成新结点*/
huffmanTree[i].rchild=s2;
huffmanTree[i].weight=huffmanTree[s1].weight+huffmanTree[s2].weight;
}
}

/*编码*/
void HuffmanCoding(int n)
{
int i,j;
int start;
int current,father;
char* cd=(char*)malloc(n*sizeof(char));
cd[n-1]='/0';
for(i=0;i<n;i++)
{
start=n-1;
current=i;
father=huffmanTree[i].parent;
while(father)
{
if(huffmanTree[father].lchild==current)
cd[--start]='0';  /*父结点的左边设为0*/
else
cd[--start]='1';  /*父结点的左边设为1*/
current=father;
father=huffmanTree[father].parent;
}
huffmanCode[i]=(char*)malloc((n-start)*sizeof(char));
strcpy(huffmanCode[i],&cd[start]);
}
free(cd);
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：30301次
• 积分：548
• 等级：
• 排名：千里之外
• 原创：25篇
• 转载：0篇
• 译文：0篇
• 评论：9条
文章分类
文章存档
最新评论
神州夜航