@【数据结构】(二叉树-哈夫曼树及哈夫曼编码)
实现哈夫曼树的创建算法,并按哈夫曼树实现哈夫曼编码算法。
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<iomanip>
#define MAXVALUE 10000
#define MAXLEAF 30 // 叶子结点数
#define MAXNODE MAXLEAF*2-1 //树中结点总数
using namespace std;
typedef struct
{
int weight;
int parent;
int lchild;
int rchild;
}Hnode, HuffmanTree[MAXNODE];
typedef struct codenode
{
char ch; //存放要表示的符号
char code[MAXLEAF]; // 存放相应代码
}CodeNode;
typedef CodeNode HFCode[MAXLEAF];
void createHT(HuffmanTree ht, int w[], int n) // w传递n个权值
{
int i, j, m1, m2, x1, x2;
for (i = 0; i < 2 * n-1; i++) // 所有结点的相关域置初值-1
{
ht[i].parent = ht[i].lchild = ht[i].rchild = 0;
ht[i].weight = 0;
}
//赋权值
for (i = 0; i < n; i++)
ht[i].weight = w[i];
for (i = 0; i < n-1 ; i++)
{
m1 = m2 = MAXVALUE;
x1 = x2 = 0;
for (j = 0; j <n + i; j++) // 寻找权值最小的两颗子树
{
if (ht[j].weight < m1&&ht[j].parent == 0)
{
m2 = m1; x2 = x1; x1 = j;
m1 = ht[j].weight; // 次小
}
else if (ht[j].weight < m2&&ht[j].parent == 0)
{
m2 = ht[j].weight;
x2 = j; //最小
}
}
//将找出的两颗子树合并为一颗子树
ht[x1].parent = n + i; ht[x2].parent = n + i;
ht[n + i].weight = ht[x1].weight + ht[x2].weight;
ht[n + i].lchild = x1;
ht[n + i].rchild = x2;
}
}
void outputTree(HuffmanTree ht,int n)
{
cout << "序号 weight parent leftchild rightchild" << endl;
for (int i = 0; i < n * 2-1; i++)
{
cout << setw(3) << i;
cout << setw(4) << ht[i].weight;
cout << setw(4) << ht[i].parent;
cout << setw(4) << ht[i].lchild;
cout << setw(4) << ht[i].rchild << endl;
}
cout << endl;
}
void createHFCode(HuffmanTree ht, HFCode &hc, int n) //从叶子到根,逆向搜索
{
char code[10];
int i, c, p, start;
cout << "输入相应待编码字符(8):" << endl;
for (i = 0; i < n; i++)
cin >> hc[i].ch;
code[n - 1] = '\0'; // 从左到右逐位存放编码,首先存放结束符
for (i =0; i <= n; i++) //求n个结点对应的哈夫曼编码
{
start = n - 1;
c = i; p = ht[i].parent;
while (p != 0)
{
--start;
if (ht[p].lchild == c) // 左子树
code[start] = '0';
else code[start] = '1'; //右子树
c = p;
p = ht[p].parent; //向上倒推
}
strcpy(hc[i].code, &code[start]); // 将工作区中的编码复制到编码表中
}
}
void outputCode(HFCode hc, int n)
{
for (int i = 0; i <n ; i++)
{
cout << hc[i].ch << "->" << hc[i].code << endl;
}
cout << endl;
}
void main()
{
HuffmanTree ht;
HFCode hc;
int w[10];
int i, j, n;
cout << "请输入哈弗曼树叶子结点的权值(8):" << endl;
for (i = 0; i < 8; i++)
cin >> w[i];
createHT(ht, w,8);
outputTree(ht, 8);
createHFCode(ht, hc, 8);
outputCode(hc, 8);
system("pause");
}
测试: