#include<iostream>
#include<algorithm>
using namespace std;
struct Tree
{
double data;
Tree *lChild, *rChild;
Tree *fater;
};
/*创建哈夫曼树*/
void buildHFM(Tree *t[]);
/*获取编码*/
void getWay(Tree *node[], int n);
void getFat(Tree *root);
int cod[20] = { 0 };//存储哈夫曼树编码
int a, b;//跟踪数组的下标,做删除和增加操作
int k;//记录编码的长度
int main()
{
int n;
cout << "请输入结点的个数:";
cin >> n;
a = 0;
b = n - 1;
Tree **node = new Tree*[n];
Tree **t = new Tree*[2*n];
cout << "请输入结点的权值:" << endl;
//对结点的属性进行初始化
for (int i = 0; i < n; i++)
{
node[i] = t[i] = new Tree;
cin >> t[i]->data;
t[i]->fater = t[i]->lChild = t[i]->rChild = NULL;
}
//进行第一次排序
sort(t, t + n, [](Tree *a, Tree *b) {return a->data < b->data; });
//创建哈夫曼树
buildHFM(t);
//获取编码
cout <<"编码为分别为:" << endl;
getWay(node, n);
system("pause");
return 0;
}
void buildHFM(Tree *t[])
{
double sum;
while (a < b)
{
sum = t[a]->data + t[a + 1]->data;
b++;//b加1
//加入新结点并刷新其属性
t[b] = new Tree;
t[b]->data = sum;
if (t[a]->data > t[a + 1]->data)
{
t[b]->lChild = t[a];
t[b]->rChild = t[a + 1];
t[b]->fater = NULL;
}
else
{
t[b]->rChild = t[a];
t[b]->lChild = t[a + 1];
t[b]->fater = NULL;
}
//刷新两个子结点的父结点
t[a]->fater = t[a + 1]->fater = t[b];
a += 2;//a往后移两位
int index = b;
int index2 = b-1;
//重新排序序列
while (t[index]->data <= t[index2]->data)
{
swap(t[index--], t[index2--]);
if (index2 < a)//小于新初始结点,退出
break;
}
}
}
void getWay(Tree *node[], int n)
{
int i = 0;
while (i < n)
{
k = 0;//编码长度初始化为0
getFat(node[i++]);//依次获取父结点
//输出编码
cout << node[i - 1]->data << " :";
for (int j = k - 1; j >= 0; j--)
{
cout << cod[j];
}
cout << endl;
}
}
void getFat(Tree *root)
{
if (root->fater == NULL)
return;
Tree *T = root->fater;
if (T->lChild == root)
cod[k++] = 0;
else
cod[k++] = 1;
getFat(T);
}
哈夫曼树编码问题
猜你喜欢
转载自blog.csdn.net/qq_43703976/article/details/90348374
今日推荐
周排行