哈夫曼树的建立及编码 C语言

哈夫曼树的建立及编码

#include
#include
#define N 20
#define M 2*N-1

typedef struct{
     
	int weight;  //权值
	int parent;  //双亲
	int lchild;   //左孩子
	int rchild;   //右孩子
}huffmantree;

typedef struct{
     
	int start;  
	char codes[N];   //存哈夫曼的编码
}huffmancode;

void creathuffman(huffmantree tree[],int n){
     
	int i,j,w,p1,p2,small1,small2;
	int m = 2*n;
	for (i=1;i<m;i++){
           //初始化
		tree[i].weight = 0;
		tree[i].lchild = 0;
		tree[i].rchild = 0;
		tree[i].parent = 0;
	}
	printf("input weight:");
	for (i=1;i<=n;i++){
         //输入每个点的权值
	    scanf("%d",&w);
		tree[i].weight = w;	
	}
	for(i=1;i<m;i++){
     
		printf("%d  %d  %d  %d\n",tree[i].weight,tree[i].parent,tree[i].lchild,tree[i].rchild);
	}
	for(i=n+1;i<m;i++)  //比较选出权值的最小值和次小值
	{
     
		p1=0;
		p2=0;
		small1 = 10000;
		small2 = 10000;
		for(j=1;j<i;j++)
		{
     
			if(tree[j].parent==0)
			{
     
				if(tree[j].weight<small1)
				{
     
					small2 = small1;
					small1 = tree[j].weight;
					p2 = p1;
					p1 = j;
				}
				else
					if(tree[j].weight<small2)
					{
     
						small2 = tree[j].weight;
						p2 = j;
					}
			}
		}
		tree[i].weight = (tree[p1].weight+tree[p2].weight);
	 	tree[i].lchild = p1;
	 	tree[i].rchild = p2;
		tree[p1].parent = i;
		tree[p2].parent = i;
	}
}

void codehuffman(huffmantree *tree,huffmancode *code,int n){
     
	huffmancode temp;
	int i,c,p;
	for(i=1;i<=n;i++){
     
		temp.start = n;
		c = i;
		p = tree[i].parent;
		while(p!=0){
     
			--temp.start;
			if (tree[p].lchild == c)
				temp.codes[temp.start] = '0';
			else
				temp.codes[temp.start] = '1';
			c = p;
			p = tree[p].parent;
		}
		code[i] = temp;
	}
}
				


void main(){
     
	int n,i,j;
	huffmantree tree[M];
	huffmancode code[N];
	printf("input str nums:");
	scanf("%d",&n);
	creathuffman(tree,n);
	codehuffman(tree,code,n);
	for(i=1;i<=(2*n)-1;i++)
		printf("%d   %d   %d   %d\n",tree[i].weight,tree[i].parent,tree[i].lchild,tree[i].rchild);
	for(i=1;i<=n;i++){
     
		for(j=code[i].start;j<=n;j++)
		{
     
			printf("%c",code[i].codes[j]);
		
		}putchar('\n');
	}
}

你可能感兴趣的:(c数据结构,哈夫曼树,哈夫曼树的建立及编码)