算法:Haffman,DFS
数据结构:queue,Haffman Tree
PS:使用链表建树,但用数组存树操作更方便
// Huffman.cpp : 定义控制台应用程序的入口点。
//
//#include "stdafx.h"
#include "iostream"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "string"
#include "queue"
#include "fstream"
const int max_nodenum=100; //最多字符数
using namespace std;
struct Node
{
char ch;
double weight;
Node* parent;
Node* Lchild;
Node* Rchild;
Node()
{
ch = NULL;
weight = 0;
parent = NULL;
Lchild = NULL;
Rchild = NULL;
}
bool operator < (const Node &a)const
{
return a.weight < weight;
}
}Hf[max_nodenum]; //Hf[n]用来存储符号信息,和建树无关
struct Info //打表保存字符编码信息
{
char ch;
string code;
}info[max_nodenum];
Node *root; //huffman树根
void CreateTree()
{
root = new Node;
priority_queue <Node> Queue;
ifstream fin("hfmTree.txt"); //在文件中读取已保存的数据
int n;
fin >> n;
for (int i = 0; i < n; i++)
{
fin >> Hf[i].ch >> Hf[i].weight;
Queue.push(Hf[i]);
}
while (Queue.size() > 1) //建树 从下向上
{
Node* a = new Node; //左子树
if (Queue.top().ch == NULL)
{
*a = Queue.top();
a->Lchild->parent = a; //***被坑了好久
a-