哈弗曼树的创建及哈弗曼编码

今天晚上花了好几个小时写了这个程序。。。都怪我效率太低。。。

好了废话不多说,下面就给出我的代码。(这个代码参考了 严蔚敏老师 的算法)

其中具体的实现就不多讲,因为我在注释都写了。

 

#include<iostream>
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;
	cout<<"Please input the count of the number:";
	cin>>nn;
	weight = (int*)malloc(nn*sizeof(int));
	cout<<"Input the data one by one:"<<endl;
	for(i = 0; i < nn; i ++)
	{
		cin>>weight[i];
	}
	HuffEncoding(nn,weight,tree,codes);
	for(i = 1; i <= nn; i ++)
	{
		printf("%d:%s\n",tree[i].weight,codes[i]);
	}
	return 0;
}

 

    原文作者:哈夫曼树
    原文地址: https://blog.csdn.net/lingyb011/article/details/83609475
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞