6.2: 哈夫曼树

#include<iostream>
#include <fstream>
#include <string.h>
using namespace std; 
#define MaxSize 1024  // 读入文件的上限 
#define OK 1
#define ERROR 0
typedef int Status;
typedef struct wordcnt{  // 统计字符和对应的次数 
	char ch;
	int cnt = 0;
}Count;
typedef struct NumCount{  // 统计次数的外部封装 
	Count count[MaxSize];
	int length = 0;
}NumCount;
typedef struct HTree{  // 哈夫曼树结构 
	char data; 
	int weight;
	int parent,lchild,rchild;
}HTNode,*HuffmanTree; 
typedef struct HCode{ // 编码结构 
	char data;
	char* str; 
}*HuffmanCode;
Status ReadData(char *source);  // 读入文件 
Status WordCount(char *data,NumCount *paraCnt); // 统计次数 
Status Show(NumCount *paraCnt);   // 展示次数 
Status CreateHuffmanTree(HuffmanTree &HT,int length,NumCount cntarray);  // 创建哈夫曼树 
Status select(HuffmanTree HT,int top,int *s1,int *s2);  // 选择权重最小的两个节点 
Status CreateHuffmanCode(HuffmanTree HT,HuffmanCode &HC,int length);  // 创建哈夫曼编码 
Status Encode(char *data,HuffmanCode HC,int length);  // 将读入的文件编码,写到txt文件 
Status Decode(HuffmanTree HT,int length);  //读入编码文件,解码 
int main(int argc, char** argv) {
	char data[MaxSize];  
	NumCount Cntarray;
	ReadData(data);  // 读入数据 
	WordCount(data,&Cntarray);  // 统计次数 
//	Show(&Cntarray); //可以查看每个单词出现的对应次数 
	HuffmanTree tree;
	CreateHuffmanTree(tree,Cntarray.length,Cntarray);  // 建树 
	HuffmanCode code;  
	CreateHuffmanCode(tree,code,Cntarray.length);  // 创建编码 
	Encode(data,code,Cntarray.length);  // 生成编码文件 
	Decode(tree,Cntarray.length);  // 解码 
	cout<<"Please view the generated TXT file to check the result"<<endl; 
	return 0;
}
Status ReadData(char *source)
{
	//打开文件读入数据 
	ifstream infile;
	infile.open("in.txt");
	cout<<"Reading..."<<endl;
	cout<<"the input file is:"<<endl;
	infile.getline(source,MaxSize);
	cout<<source<<endl;
	infile.close();
	cout<<endl;
	return OK;
}
Status WordCount(char *data,NumCount *paraCnt)
{
	int flag;// 标识是否已经记录 
	int len = strlen(data);
	for(int i = 0;i < len;++i)
	{
		flag = 0;
		for(int j = 0;j < paraCnt->length;++j)
		{
			if(paraCnt->count[j].ch == data[i]) // 若已有记录,直接++ 
			{
				++paraCnt->count[j].cnt;
				flag = 1;
				break;
			}
		}
		if(!flag) // 没有记录,则新增 
		{
			paraCnt->count[paraCnt->length].ch = data[i];
			++paraCnt->count[paraCnt->length].cnt;
			++paraCnt->length;
		}
	}
	return OK;
}
Status Show(NumCount *paraCnt)
{
	cout<<"the length is "<<paraCnt->length<<endl;
	for(int i = 0;i < paraCnt->length;++i)
	{
		cout<<"The character "<<paraCnt->count[i].ch<<"  appears  "<<paraCnt->count[i].cnt<<endl;
	}
	cout<<endl;
	return OK;
}
Status CreateHuffmanTree(HuffmanTree &HT,int length,NumCount cntarray)
{
	if(length <= 1) return ERROR;
	int s1,s2;
	int m = length*2-1;  // 没有度为1的节点,则总结点是2*叶子节点数-1个 
	HT = new HTNode[m+1];
	for(int i = 1;i <= m;++i)  // 初始化 
	{
		HT[i].parent = 0;
		HT[i].lchild = 0;
		HT[i].rchild = 0;
	}
	for(int i = 1;i <= length;++i) 
	{
		HT[i].data = cntarray.count[i-1].ch;
		HT[i].weight = cntarray.count[i-1].cnt;
	}
	for(int i = length + 1;i <= m;++i)
	{
		select(HT,i-1,&s1,&s2);  // 从前面的范围里选择权重最小的两个节点 
		HT[s1].parent = i;
		HT[s2].parent = i;
		HT[i].lchild = s1;
		HT[i].rchild = s2;
		HT[i].weight = HT[s1].weight + HT[s2].weight;  // 得到一个新节点 
	}
	return OK;
}
Status select(HuffmanTree HT,int top,int *s1,int *s2)
{
	int min = INT_MAX;
	for(int i = 1;i <= top;++i)  // 选择没有双亲的节点中,权重最小的节点 
	{
		if(HT[i].weight < min && HT[i].parent == 0)
		{
			min = HT[i].weight;
			*s1 = i;
		}
	}
	min = INT_MAX;
	for(int i = 1;i <= top;++i)  // 选择没有双亲的节点中,权重次小的节点 
	{
		if(HT[i].weight < min && i != *s1 && HT[i].parent == 0)
		{
			min = HT[i].weight;
			*s2 = i;
		}
	}
	return OK;	
}
Status CreateHuffmanCode(HuffmanTree HT,HuffmanCode &HC,int length)
{
	HC = new HCode[length+1];
	char *cd = new char[length];  // 存储编码的临时空间 
	cd[length-1] = '\0';  // 方便之后调用strcpy函数 
	int c,f,start;
	for(int i = 1;i <= length;++i)
	{
		start = length-1;  // start表示编码在临时空间内的起始下标,由于是从叶子节点回溯,所以是从最后开始 
		c = i;
		f = HT[c].parent;
		while(f != 0)
		{
			--start;  // 由于是回溯,所以从临时空间的最后往回计 
			if(HT[f].lchild == c)
				cd[start] = '0';
			else 
				cd[start] = '1';
			c = f;
			f = HT[c].parent;
		}
		HC[i].str = new char[length-start];  // 最后,实际使用的编码空间大小是length-start 
		HC[i].data = HT[i].data;
		strcpy(HC[i].str,&cd[start]);  // 从实际起始地址开始,拷贝到编码结构中 
	}
	delete cd;
}
Status Encode(char *data,HuffmanCode HC,int length)
{
	ofstream outfile;
	outfile.open("code.txt");
	for(int i = 0;i < strlen(data);++i)  // 依次读入数据,查找对应的编码,写入编码文件 
	{
		for(int j = 1;j <= length;++j)
		{
			if(data[i] == HC[j].data)
			{
				outfile<<HC[j].str;
			}
		}
	}
	outfile.close();
	cout<<"the code txt has been written"<<endl;
	cout<<endl;
	return OK;
}
Status Decode(HuffmanTree HT,int length)
{
	char codetxt[MaxSize*length];
	ifstream infile;
	infile.open("code.txt");
	infile.getline(codetxt,MaxSize*length);
	infile.close();
	ofstream outfile;
   	outfile.open("out.txt");
	int root = 2*length-1;  // 从根节点开始遍历 
	for(int i = 0;i < strlen(codetxt);++i)
	{
		if(codetxt[i] == '0') root = HT[root].lchild;  //为0表示向左遍历 
		else if(codetxt[i] == '1') root = HT[root].rchild; //为1表示向右遍历 
		if(HT[root].lchild == 0 && HT[root].rchild == 0)  // 如果已经是叶子节点,输出到输出文件中,然后重新回到根节点 
		{
			outfile<<HT[root].data;
			root = 2*length-1;
		}
	}
	outfile.close();
	cout<<"the output txt has been written"<<endl;
	cout<<endl;
	return OK;
}

运行结果:

Reading...
the input file is:
  1. 从文件中读文本;
  2. 统计字符频次, 并建立字母表;
  3. 构造 Huffman 树;
  4. 将文本编码;
  5. 解码.

给定 n 个权值作为 n 个叶子节点,构造一棵二叉树,若该树的带权路径长度(Weighted Path Length of Tree)达到最小, 称这样的二叉树为最优二叉树,也称为哈夫曼树(Huffman Tree)。 哈夫曼树是带权路径长度最短的树,权值较大的节点离根较近。

哈夫曼树的重要概念
1、路径和路径长度:在一棵树中,从一个结点往下可以达到的孩子或孙子结点之间的通路,称为路径。通路中分支的数目称为路径长度。若规定根结点的层数为1,则从根结点到第L层结点的路径长度为L-1
2、结点的权及带权路径长度:若将树中结点赋给一个有着某种含义的数值,则这个数值称为该结点的权。结点的带权路径长度为:从根结点到该结点之间的路径长度与该结点的权的乘积
3、树的带权路径长度:树的带权路径长度规定为所有叶子结点的带权路径长度之和,记为WPL(weighted path length) ,权值越大的结点离根结点越近的二叉树才是最优二叉树
4、WPL最小的二叉树就是赫夫曼树

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
#include <stdio.h> #include <stdlib.h> #define MAX_SIZE 100 typedef struct TreeNode { int weight; // 权值 int parent; // 父节点 int left; // 左孩子 int right; // 右孩子 } TreeNode; typedef struct { int size; // 堆的大小 TreeNode nodes[MAX_SIZE]; // 堆的数组 } Heap; // 初始化堆 void initHeap(Heap *heap) { heap->size = 0; } // 插入一个节点到堆中 void insertNode(Heap *heap, TreeNode node) { if (heap->size == MAX_SIZE) { printf("Heap is full.\n"); return; } heap->size++; heap->nodes[heap->size] = node; int i = heap->size; while (i > 1 && heap->nodes[i].weight < heap->nodes[i / 2].weight) { TreeNode temp = heap->nodes[i]; heap->nodes[i] = heap->nodes[i / 2]; heap->nodes[i / 2] = temp; i = i / 2; } } // 弹出堆顶的节点 TreeNode popNode(Heap *heap) { if (heap->size == 0) { printf("Heap is empty.\n"); exit(1); } TreeNode node = heap->nodes[1]; heap->nodes[1] = heap->nodes[heap->size]; heap->size--; int i = 1; while (i * 2 <= heap->size) { int left = i * 2; int right = i * 2 + 1; int min = left; if (right <= heap->size && heap->nodes[right].weight < heap->nodes[left].weight) { min = right; } if (heap->nodes[min].weight < heap->nodes[i].weight) { TreeNode temp = heap->nodes[i]; heap->nodes[i] = heap->nodes[min]; heap->nodes[min] = temp; i = min; } else { break; } } return node; } // 构造哈夫曼树 void buildHuffmanTree(Heap *heap, int n) { for (int i = 1; i < n; i++) { TreeNode node1 = popNode(heap); TreeNode node2 = popNode(heap); TreeNode newNode; newNode.weight = node1.weight + node2.weight; newNode.left = node1.weight < node2.weight ? node1.parent : node2.parent; newNode.right = node1.weight < node2.weight ? node2.parent : node1.parent; newNode.parent = -1; insertNode(heap, newNode); heap->nodes[node1.parent].parent = heap->size; heap->nodes[node2.parent].parent = heap->size; } } int main() { // 构造堆 Heap heap; initHeap(&heap); int n; printf("Please input the number of nodes: "); scanf("%d", &n); for (int i = 0; i < n; i++) { TreeNode node; printf("Please input the weight of node %d: ", i); scanf("%d", &node.weight); node.parent = -1; node.left = -1; node.right = -1; insertNode(&heap, node); } // 构造哈夫曼树 buildHuffmanTree(&heap, n); // 输出哈夫曼树 printf("The Huffman tree:\n"); for (int i = 1; i <= heap.size; i++) { printf("%d %d %d %d\n", heap.nodes[i].weight, heap.nodes[i].parent, heap.nodes[i].left, heap.nodes[i].right); } return 0; }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值