哈夫曼树编码的实现

# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>
# include <string.h>
# include <limits.h>
/*
不等长的 哈夫曼前缀码(防止重码)
*/
//数据类型定义
typedef char **HuffmanCode;

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

void Select_Min(const HTree T, int lenght, int *e1, int *e2 );
void Create_Huffman(HTree *T, int n); //创建哈夫曼树
HuffmanCode Create_HuffmanCode(const HTree HT, int n); //哈夫曼编码

HuffmanCode Create_HuffmanCode(const HTree HT, int n)
{
	//HC不使用0号下标
	HuffmanCode HC = (char **)malloc(sizeof(char*)*(n+1));//用于存放编码后的字符串
	char* temp_string = (char*)malloc(sizeof(char)*n); // 次数组使用0号
	temp_string[n-1] = '\0'; //数组第n个字符为‘\0’

	for(int i=1; i<n+1; i++)
	{ //逐个字符求哈夫曼编码
		int parent = HT[i].parent;//需要回溯
		int current = i;//回溯的当前结点
		int start = n-1; //编码起点(逆向存入temp_string)
		
		while(parent)
		{//开始编码
			if(current == HT[parent].lchild)
				temp_string[--start] = '0';
			else
				temp_string[--start] = '1';

			current = parent; 
			parent = HT[parent].parent;
		} //编码结束之后形成的字符串存放HC中

		HC[i] = (char*)malloc(sizeof(char)*(n-start));
		strcpy(HC[i], &temp_string[start]);

	}
	free(temp_string);
	return HC;
}


//前置函数,选取两个结点最小值
void Select_Min(const HTree T, int lenght, int *e1, int *e2 )
{
	int min1, min2; 
	min1 = min2 = INT_MAX;
	int pos1, pos2;
	pos1 = pos2 = 0;

	for(int i=1; i<lenght+1; i++)
	{
		if(T[i].parent == 0)
		{ //!parent == 0 说明在森林里
			if(T[i].weight < min1)
			{
				min2 = min1;
				pos2 = pos1;
				min1 = T[i].weight;
				pos1 = i;
			}
			else if (T[i].weight < min2)
			{
				min2 = T[i].weight;
				pos2 = i;
			}
		}
	}
	*e1 = pos1;
	*e2 = pos2;
}


void Create_Huffman(HTree *T, int n)
{
	if (n <= 1)
		return;
	int m = 2*n - 1; //一共产生m个结点

	*T = (HTree)malloc(sizeof(HTNode) * (m+1)); //0号位置不用
    
	for(int k=1; k<m+1; k++)
	{ //Step1:初始化  
		(*T)[k].lchild = (*T)[k].rchild = 0;
		(*T)[k].parent = 0;
	}

	for(int i=1; i<n+1; i++)
	{ //输入权值
		scanf(" %d", &(*T)[i].weight);
	}
	
	//Step2:创建哈夫曼树
	int min1, min2; //最小和次小
	for (int j=n+1; j<m+1; j++)
	{
		Select_Min(*T, j-1, &min1, &min2); //核心语句

		(*T)[min1].parent = (*T)[min2].parent = j;
		(*T)[j].lchild = min1; //设置左孩子
		(*T)[j].rchild = min2; //设置右孩子
		(*T)[j].weight = (*T)[min1].weight + (*T)[min2].weight; //权值相加生新树		
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值