哈夫曼树各种函数

HuffmanTree.h

#ifndef HUFFMANTREE_H
#define HUFFMANTREE_H
#include
#include
using namespace std;
struct HuffmanNode
{
	char data;
	double weight;
	int parent,lchild,rchild;
};
class HuffmanTree
{
private:
	vector<HuffmanNode> hufftree;
	int n;
public:
	HuffmanTree(vector<HuffmanNode>&leafs);
	~HuffmanTree(){}
	vector<int> GetCode(int i);
	string Decode(vector<int> &source);
	void SelectSmall(int &least,int &less,int n);
};
#endif

HuffmanTree.cpp

#include
#include
#include
#include"HuffmanTree.h"
using namespace std;
void HuffmanTree::SelectSmall(int &least,int &less,int n)
{
	int i = 0;
	while (hufftree[i].parent!=-1 && i<n)	
		i++;
	least = i;
	i++;
	while (hufftree[i].parent!=-1 && i<n)
	i++;
	if (hufftree[i].weight < hufftree[least].weight)
		{
		  less = least;
		  least = i;
		}
	else
		{
			less = i;
		}
	for (int j = i+1;j < n;j++)
	{
		if (hufftree[j].parent != -1)
			continue;
		if (hufftree[j].weight < least)
		{
			less =least;
			least = j;
		}
		else
		if (hufftree[j].weight>=least && hufftree[j].weight<less)
			less = j;
	}
}
HuffmanTree::HuffmanTree(vector<HuffmanNode> &leafs)
{
	int i;
	int n=leafs.size();
	hufftree.resize(2*n-1);
	for(i=0;i<n;i++)
	{
		hufftree[i].data=leafs[i].data;
		hufftree[i].weight=leafs[i].weight;
		hufftree[i].parent=hufftree[i].lchild=hufftree[i].rchild=-1;
	}
	for(i=n;i<2*n-1;i++)
	{
		int least,less;
		SelectSmall(least,less,i);
		hufftree[least].parent =hufftree[less].parent=i;
		hufftree[i].parent=-1;
		hufftree[i].lchild=least;
		hufftree[i].rchild=less;
		hufftree[i].weight=hufftree[least].weight+hufftree[less].weight;
	}
}
vector <int> HuffmanTree::GetCode(int i)
{
	vector<int> code;
	int p=i;
	int parent=hufftree[i].parent;
	while(parent!=-1)
	{
		if (hufftree[parent].lchild==p)
			code.insert(code.begin (),0);
		else
			code.insert (code.begin (),1);
		p=parent;
		parent=hufftree[parent].parent;
	}
	return code;
}
string HuffmanTree::Decode(vector<int>&source)
{
	string target="";
	int root=hufftree.size ()-1;
	int p=root;
	int i;
	for(i=0;i<source.size ();i++)
	{
		if(source[i]==0)
			p=hufftree[p].lchild ;
		else
			p=hufftree[p].rchild;
		if(hufftree[p].lchild ==-1&&hufftree[p].rchild==-1)
		{
			target=target+hufftree[p].data;
			p=root;
		}
	}
	return target;
}

main.cpp

#include
#include
#include
#include"HuffmanTree.h"
using namespace std;
void main()
{
	vector <HuffmanNode> a;
	HuffmanNode a1;
	int i,j;
	char c;
	double w;
	cout<<"请输入元素值(5个数据与权值):"<<endl;
	for (i = 0;i<5;i++)
	{
		cin>>c>>w;
		
		a1.data = c;
		a1.weight = w;
		a.push_back(a1);
	}
	HuffmanTree t(a);
	vector<int> num;
	string s;
	for (i =0;i<5;i++)
	{
		num = t.GetCode(i);
		cout<<"第"<<i<<"个元素的编码为:";
		for (j = 0;j<num.size();j++)
			cout<<num[j];
		cout<<endl;
		cout<<"此编码对应的元素为:"<<endl;
		s=t.Decode(num);
		cout<<s<<endl;
	}
}

你可能感兴趣的:(数据结构学习,c++,数据结构)