Huffman Tree -- Huffman编码

#include <stdlib.h>  
#include <stdio.h>  
#include <string.h>
typedef struct HuffmanTree  
{	
	int weight;  
	int parent, lchild, rchild;  
}HuffmanTree;   
typedef struct CodeNode  
{
	int ch;  
	char bits[4+1];  
}CodeNode;  
void SelectMin(HuffmanTree tree[], int len, int * pos1, int* pos2)  
{
	int min=255;  
	int i, j;  
	*pos1=0;  
	*pos2=0;  
	for(i=0; i<len; i++)  
	{	
		if(tree[i].parent==-1)  
			if(min>tree[i].weight)  
			{  
			min=tree[i].weight;  
			*pos1=i;  
		}  
	}  
   min=255;  
   for(j=0; j<len; j++)  
   {  
		if(j==*pos1)  
			continue;  
		if(tree[j].parent==-1)  
			if(min>tree[j].weight)  
			{  
				min=tree[j].weight;  
				*pos2=j;  
		}  
	}  
}   
void CreateHuffmanTree(HuffmanTree tree[], int n)  
{	
	int m=2*n;  
	int i;  
	for(i=n; i<m-1; i++)  
	{  
		int pos1, pos2;  
		HuffmanTree node;  
		SelectMin(tree, i, &pos1, &pos2);
		printf("pos1=%d,pos2=%d\n", pos1, pos2);  
		node.weight=tree[pos1].weight+tree[pos2].weight;  
		tree[pos1].parent=i;  
		tree[pos2].parent=i;  
		node.lchild=pos1;  
		node.rchild=pos2;  
		node.parent=-1;  
		tree[i]=node;  
	}  
}   
void HuffmanEncoding(HuffmanTree tree[])  
{	
	int c, p, i;  
	int start;  
	char cd[4+1];  
	cd[4]='\0';    
	for(i=0; i<4; i++)  
	{  
		printf("\n");  
		printf("%d",tree[i].weight);  
		printf(":");  
		start=4;  
		c=i;  
		while((p=tree[c].parent)!=-1)  
		{  
			if(tree[p].lchild==c)  
			{  
				cd[--start]='0';  
			}  
			else  
			{  
				cd[--start]='1';  
			}  
		c=p;  
		}  
		printf(&cd[start]);  
	}  
}  
int main(int argc, char* argv[])  
{	
	HuffmanTree tree[4*2];  
	int i, j;  
	for(i=0; i<4; i++)  
	{  
		tree[i].lchild=-1;  
		tree[i].rchild=-1;  
		tree[i].parent=-1;  
	}    
	printf("请输入哈夫曼树叶子结点的权值: \n");  
	for(i=0; i<4; i++)     //读入叶子结点的权值  
	{  
		int weight;  
		scanf("%d",&weight);  
		tree[i].weight=weight;  
	}	
	CreateHuffmanTree(tree, 4);  
	for(j=0; j<2*4-1; j++)  
	{  
		printf("tree[%d]:weight=%d \n", j, tree[j].weight);  
	}  
	HuffmanEncoding(tree);       
	return 0;  
}  

 

转载于:https://my.oschina.net/u/3761238/blog/2698599

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值