哈夫曼树相关概念及C++实现

x33g5p2x  于2021-09-24 转载在 C/C++  
字(1.2k)|赞(0)|评价(0)|浏览(474)

文章目录

一,哈夫曼树基本概念

二,构造哈夫曼树

三,哈夫曼编码

四,C++实现哈夫曼树

#include<iostream>
using namespace std;
#define MaxWeight 100

typedef struct HTNode
{
	int weight;
	int parent, lch, rch;
	bool visit;
	
}HTNode, *HuffmanTree;

void Select(HuffmanTree HT, int i, int& s1, int& s2)  //挑选权值最小的两个结点 
{
	int sm1, sm2;
	sm1 = sm2 = MaxWeight;
	for(int j=0; j<=i; ++j)
	{
		if(HT[j].weight<sm1&&!HT[j].visit)
		{
			sm1 = HT[j].weight;
			s1 = j;
		}
	}
	HT[s1].visit = true;
	
	for(int j=0; j<=i; ++j)
	{
		if(HT[j].weight<sm2&&!HT[j].visit)
		{
			sm2 = HT[j].weight;
			s2 = j;
		}
	}
	HT[s2].visit = true;
}

void CreatHuffmanTree(HuffmanTree& HT, int n)
{
	int m = 2*n-1;  //数组最终有2*n-1个元素
	HT = new HTNode[m];
	for(int i=0; i<m; ++i)   //初始化各个结点 
	{
		
		HT[i].lch = HT[i].rch = HT[i].parent = -1;
		HT[i].visit = false;
	} 
	for(int i=0; i<n; ++i)  //输入各个结点的权重 
	{
		cin >> HT[i].weight;
	}
	for(int i=n; i<m; ++i)
	{
		int s1, s2;
		Select(HT, i-1, s1, s2);  //从HT[k](0=<k<=i-1)中没有双亲结点的结点中找出权重最小的两个结点的位置 
		HT[i].weight = HT[s1].weight + HT[s2].weight ;
		HT[i].lch = s1;
		HT[i].rch = s2;
		HT[s1].parent = HT[s2].parent = i;
	}
}

int main()
{
	HuffmanTree HT;
	int n = 8;
	CreatHuffmanTree(HT, n);
	for(int i=0; i<2*n-1; ++i)
	{
		cout << HT[i].weight << " " << HT[i].parent << " " << HT[i].lch << " " << HT[i].rch << endl;
	}
}

相关文章