C++ --- 哈夫曼树

#include 
#include 
#include 
#include 
#include 
using namespace std;

using uint = unsigned int;

class HuffManTree
{

public:
	HuffManTree()
		:root_(nullptr)
	{}


	~HuffManTree()
	{
		queue que;
		que.push(root_);
		while (!que.empty())
		{
			Node* cur = que.front();
			que.pop();
			if (cur->left_ != nullptr)
			{
				que.push(cur->left_);
			}

			if (cur->right_ != nullptr)
			{
				que.push(cur->right_);
			}

			delete cur;
		}
 	}

	void create(const string& str)
	{
		//存储每种字符对应个数  --- 比例
		unordered_map dataMap;
		for (auto ch : str)
		{
			dataMap[ch]++;
		}

		//创建小根堆
		using minHeap = priority_queue, function>;
		minHeap que([](Node* n1, Node* n2)->bool {return n1->weight_ > n2->weight_; });

		for (auto& pair : dataMap)
		{
			que.push(new Node(pair.first, pair.second));
		}

		while (que.size() > 1)
		{
			//取最小的两个结点
			Node* node1 = que.top();
			que.pop();
			Node* node2 = que.top();
			que.pop();

			//生成父节点
			Node* newnode = new Node('\0', node1->weight_ + node2->weight_);
			que.push(newnode);
	
			newnode->left_ = node1;
			newnode->right_ = node2;
		}
		root_ = que.top();
	}


	//压缩
	string encode(const string& str)
	{
		getHuffManTree();
		string compress;
		for (char ch : str)
		{
			compress.append(codeMap_[ch]);
		}
		return compress;
	}

	//解压缩
	string uncode(const string& str)
	{
		string uncompress;
		Node* cur = root_;

		//根据路径找到叶子结点上的字符
		for (auto ch : str)
		{
			if (ch == '0')
			{
				cur = cur->left_;
			}
			else
			{
				cur = cur->right_;
			}

			if (cur->left_ == nullptr && cur->right_ == nullptr)
			{
				uncompress.push_back(cur->data_);
				cur = root_;
			}
		}
		return uncompress;
	}

private:
	struct Node;

	void getHuffManTree()
	{
		string code;
		getHuffManTree(root_, code);
	}

	void getHuffManTree(Node* node, string code)
	{
		if (node->left_ == nullptr && node->right_ == nullptr)
		{
			codeMap_[node->data_] = code;  //将每个字符对应的编码存入map
			return;
		}

		getHuffManTree(node->left_, code + "0");
		getHuffManTree(node->right_, code + "1");
	}

private:

	struct Node
	{
		Node(char data, uint weight)
			:data_(data)
			, weight_(weight)
			, left_(nullptr)
			, right_(nullptr)
		{}

		char data_;
		uint weight_;
		Node* left_;
		Node* right_;
	};

	

private:
	Node* root_;
	unordered_map codeMap_;  //字符对应的编码
};

int main()
{
	string str = "abcdefdasdasddfh";
	HuffManTree tree;
	tree.create(str);
	string encode = tree.encode(str);
	string uncode = tree.uncode(encode);
	cout << encode << endl;
	cout << uncode << endl;
	return 0;
}

你可能感兴趣的:(力扣刷题栏,c++)