当前位置:   article > 正文

空间数据结构--哈夫曼树

空间数据结构--哈夫曼树

6.3 遍历二叉树和线索二叉树

6.3.1 遍历二叉树

二叉树的3个基本单元:根节点、左子树、右子树

若限定先左后右可分为:先序遍历、中序遍历、后序遍历

先序遍历:

  1. void printBT(BinTree* T) {
  2. if (T == NULL) {
  3. printf("空\n");
  4. return;
  5. }
  6. else {
  7. printf("%c ", T->data);
  8. printBT(T->lchild);
  9. printBT(T->rchild);
  10. }
  11. }

中序遍历:

  1. void printBT2(BinTree* T) {
  2. if (T == NULL) {
  3. printf("空\n");
  4. return;
  5. }
  6. else {
  7. printBT2(T->lchild);
  8. printf("%c ", T->data);
  9. printBT(T->rchild);
  10. }
  11. }

后序遍历:

  1. void printBT2(BinTree* T) {
  2. if (T == NULL) {
  3. printf("空\n");
  4. return;
  5. }
  6. else {
  7. printBT2(T->lchild);
  8. printBT(T->rchild);
  9. printf("%c ", T->data);
  10. }
  11. }

树与表达式:

Q1:已知树->后序表达式->逆波兰式计算

Q2:已知有先序和中序->推算出后序

先序:a b d e c f g h i

中序:  d e b a f c h g i

复原二叉树并求出后序:

6.6 赫夫曼树

赫夫曼(Huffman)树,又称最优树,是一类带权路径长度最短的树,有着最广泛的应用

6.6.1最优二叉树(哈夫曼树)

路径:从树中一个结点到另一个结点之间的分支构成这两个结点之间的路径

路径长度:路径上的分支数目

树的路径长度:从树根到每一结点的路径长度之和

结点的带权路径长度:结点权与该结点到树根之间的路径长度乘积

树的带权路径长度:……

最优二叉树/哈夫曼树:带权路径长度最小的二叉树

哈夫曼算法叙述:

(1)根据给定n个权值构成n棵二叉树的集合,F={T1,T2,T2……},每棵二叉树Ti中只有一个带权wi的根节点,其左右子树均空

(2)F中选取两颗根结点的权值最小的树作为左右子树,作为左右子树构造一棵新的二叉树,且重置新的二叉树的根结点的权值为其左、右子树上根结点的权值之和

(3)删除这两棵树,将新树加入

(4)重复

6.6.2哈夫曼编码

基础:创建哈夫曼树

上机要求:根据序列与权重,生成哈夫曼树

init code    by 废阿柴    2024/04/22

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<memory.h>
  4. typedef struct {
  5. char ch;
  6. unsigned weight;
  7. int parent, lchild, rchild;
  8. }HTNode;
  9. const char* infilename = "D:\\c practice data\\huffman_source.txt";
  10. const unsigned int Min=65535;
  11. //1.创建哈夫曼树
  12. HTNode* createHuffTree(const char* infilename,int *n);
  13. //1.1打印HuffTree
  14. void printHuffTree(HTNode* hTree,int n);
  15. //1.2打印每个字符的huffman编码
  16. void printHuffCode(HTNode* hTree, int i);
  17. //找到最小权重的下标
  18. int findMin(HTNode* Htree, int i);
  19. int main() {
  20. int n=0;
  21. HTNode* Htree = createHuffTree(infilename,&n);
  22. printHuffTree(Htree,n);
  23. for (int i = 0; i < n; i++) {
  24. printf("%c %d:",Htree[i].ch,Htree[i].weight);
  25. printHuffCode(Htree, i);
  26. printf("\n");
  27. }
  28. free(Htree);
  29. return 0;
  30. }
  31. //1.创建哈夫曼树
  32. HTNode* createHuffTree(const char* infilename, int* n) {
  33. //1.打开文件
  34. FILE* fp = fopen(infilename, "r");
  35. if (fp == NULL) {
  36. printf("error\n");
  37. return NULL;
  38. }
  39. fscanf(fp, "%d\n", n);
  40. HTNode* Htree = (HTNode*)malloc((2*(*n) - 1)*sizeof(HTNode));
  41. memset(Htree, 0, (2 * (*n) - 1) * sizeof(HTNode));
  42. //2.初始化哈夫曼树
  43. for (int i = 0; i < (*n);i++) {
  44. char ch;
  45. int weight;
  46. fscanf(fp, "%c %d\n", &ch, &weight);
  47. Htree[i].ch = ch;
  48. Htree[i].weight = weight;
  49. Htree[i].parent = Htree[i].lchild=Htree[i].rchild=-1;
  50. }
  51. fclose(fp);
  52. //3.利用算法重建哈夫曼树
  53. for (int i = (*n); i < (*n)*2 - 1; i++)//这是因为n后都是空的,不需要找
  54. {
  55. int n1 = findMin(Htree, i);
  56. int n2 = findMin(Htree, i);
  57. Htree[i].parent = -1;
  58. Htree[i].lchild = n1;
  59. Htree[i].rchild = n2;
  60. Htree[i].weight = Htree[n1].weight + Htree[n2].weight;
  61. Htree[n1].parent = Htree[n2].parent = i;
  62. }
  63. return Htree;
  64. }
  65. //1.1打印HuffTree
  66. void printHuffTree(HTNode* hTree, int n) {
  67. for (int i = 0; i < 2*n-1; i++) {
  68. printf("%d:%c %d %d %d %d\n",i, hTree[i].ch, hTree[i].weight, hTree[i].parent, hTree[i].lchild, hTree[i].rchild);
  69. }
  70. }
  71. //1.2打印每个字符的huffman编码
  72. void printHuffCode(HTNode* hTree, int i) {
  73. int parent = hTree[i].parent;
  74. //打印的字符一定是叶子结点,那么parent一定不为-1;
  75. if (parent == -1) {
  76. return;
  77. }//递归一定要在开始时设置返回条件
  78. printHuffCode(hTree, parent);
  79. int child=-1;
  80. if (hTree[parent].lchild == i)//为什么是i?
  81. child = 0;
  82. if (hTree[parent].rchild == i)
  83. child = 1;
  84. printf("%d", child);
  85. return ;//-----------
  86. }
  87. //找到最小权重的下标
  88. //需要注意的是,有parent的不参与排序(需要排除)
  89. int findMin(HTNode* Htree, int n) {
  90. int target=-1;
  91. unsigned int finMin = Min;
  92. for (int i = 0; i < n; i++) {
  93. if ((Htree[i].weight < finMin) && Htree[i].parent ==-1) {
  94. finMin = Htree[i].weight;
  95. target = i;
  96. }
  97. }//如何找到倒数第二大的?前一个做标记
  98. Htree[target].parent = 0;//这样找n2时就排除了前一个最小的
  99. return target;
  100. }
进阶:对文本文件的英文字符利用Huffman算法进行压缩,再重新解压

上机要求:
(1)对指定的英文文本文件字符出现频率进行统计,获得权重表

(2)利用权重表创建哈夫曼树

(3)利用哈夫曼树对文本文件进行编码压缩

(4)对压缩编码进行解压缩

init code    by 废阿柴    2024/04/29

(1)定义哈夫曼树、码表结构以及压缩、解压两个函数

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4. #include<memory.h>
  5. const char* srcFilename = "D:\\c practice data\\Huffman\\no_zip.txt";
  6. const char* zipFilename = "D:\\c practice data\\Huffman\\zip.dat";
  7. const char* unzipFilename = "D:\\c practice data\\Huffman\\unzip.txt";
  8. const unsigned int Min=65536;
  9. //定义哈夫曼树
  10. typedef struct {
  11. char ch;
  12. unsigned int weight;
  13. unsigned int len;//编码长度
  14. char* code;
  15. int parent, lchild, rchild;
  16. }HTNode;
  17. //定义码表结构
  18. typedef struct {
  19. bool isValid;
  20. int len;
  21. char* code;
  22. }HTCode;
  23. //1.对文件进行压缩、构建哈夫曼树、获取压缩编码、存入文件
  24. bool huffZip(const char* srcFilename, const char* zipFilename);
  25. //创建哈夫曼树
  26. HTNode* createHuffTree(int weightTable[], int n);
  27. //找到权重最小值
  28. int findMin(HTNode* Htree, int n);
  29. //删除哈夫曼树
  30. void deleteHuffTree(HTNode* Htree, int n);
  31. //2.对已压缩文件进行解压,并且保存
  32. bool huffUnzip(const char* zipFilename, const char* unzipFilename);

位操作:方便对后续压缩编码进行按位存储

  1. // 取出index位,若取出的index位为0,则GET_BYTE 值为假,否则为真
  2. #define GET_BYTE(vbyte, index) (((vbyte) & (1 << ((index) ^ 7))) != 0)
  3. // 把index位设置为‘1’
  4. #define SET_BYTE(vbyte, index) ((vbyte) |= (1 << ((index) ^ 7)))
  5. // 把index位设置为‘0’
  6. #define CLR_BYTE(vbyte, index) ((vbyte) &= (~(1 << ((index) ^ 7))))

主函数部分

  1. int main(int argc,char*argv[])
  2. {
  3. printf("开始压缩……\n");
  4. if (huffZip(srcFilename, zipFilename)) {
  5. printf("压缩成功\n");
  6. }
  7. else {
  8. printf("压缩失败!\n");
  9. return -1;
  10. }
  11. printf("开始解压缩……\n");
  12. if (huffUnzip(zipFilename, unzipFilename)) {
  13. printf("解压缩成功\n");
  14. }
  15. else {
  16. printf("解压缩失败!\n");
  17. return -1;
  18. }
  19. return 0;
  20. }

压缩文件函数——创建二叉树+找到权重最小值+删除二叉树,释放存储空间

  1. //创建哈夫曼树
  2. HTNode* createHuffTree(int weightTable[], int n) {
  3. HTNode* Htree = nullptr;
  4. Htree = (HTNode*)malloc(sizeof(HTNode) * (2 * n - 1));
  5. memset(Htree, 0, sizeof(HTNode) * (2 * n - 1));
  6. int index = 0;
  7. for (int i = 0; i < 256; i++) {
  8. if (weightTable[i] > 0) {
  9. Htree[index].ch = (char)i;
  10. Htree[index].weight = weightTable[i];
  11. Htree[index].len = 0;
  12. Htree[index].code = nullptr;
  13. Htree[index].parent = Htree[index].lchild = Htree[index].rchild = -1;
  14. index++;
  15. }
  16. }
  17. //重新构造哈夫曼树
  18. for (int i = n; i < 2 * n - 1; i++) {
  19. int m1 = findMin(Htree, i);
  20. int m2 = findMin(Htree, i);
  21. Htree[i].weight = Htree[m1].weight + Htree[m2].weight;
  22. Htree[i].parent = -1;
  23. Htree[i].lchild = m1;
  24. Htree[i].rchild = m2;
  25. Htree[m1].parent = Htree[m2].parent = i;
  26. }
  27. return Htree;
  28. }
  29. //找到权重最小值
  30. int findMin(HTNode* Htree, int n) {
  31. int target = -1;
  32. unsigned int fMin = Min;
  33. for (int i = 0; i < n; i++) {
  34. if (Htree[i].weight < fMin && Htree[i].parent == -1) {
  35. fMin = Htree[i].weight;
  36. target = i;
  37. }
  38. }
  39. Htree[target].parent = 0;
  40. return target;
  41. }
  42. //删除哈夫曼树
  43. void deleteHuffTree(HTNode* Htree, int n) {
  44. for (int i = 0; i < n; i++) {
  45. if (Htree[i].code != nullptr) {
  46. free(Htree[i].code);
  47. }
  48. }
  49. free(Htree);
  50. return;
  51. }

1.对文件进行压缩、构建哈夫曼树、获取压缩编码、存入文件(huffZip函数)

  1. bool huffZip(const char* srcFilename, const char* zipFilename) {
  2. //1.1对文件进行读取,统计出现的字符和频率,频率作为权重
  3. FILE* fp = fopen(srcFilename, "r");
  4. int n=0;//定义字符种类总数
  5. int weightTable[256] ;
  6. memset(weightTable, 0, sizeof(int) * 255);//清除内存中的一些垃圾
  7. char ch;
  8. while (!feof(fp)) {
  9. ch = fgetc(fp);
  10. //首先先判断是否是规定的字符
  11. if (ch > 255 || ch < 0)
  12. continue;
  13. //若ch第一次出现,种类加1
  14. if (weightTable[ch] == 0) {
  15. n += 1;//
  16. }
  17. weightTable[ch]++;//每次读入一个,对应table位置+1
  18. }
  19. fclose(fp);
  20. fp=NULL;
  21. //按照权重构建哈夫曼树
  22. HTNode* Htree = createHuffTree(weightTable,n);
  23. //针对创建的Huffman树计算字符编码
  24. HTCode codeTable[256];
  25. memset(codeTable, 0, sizeof(HTCode) * 256);
  26. for (int i = 0; i < n; i++) {
  27. //从每个叶子结点开始
  28. HTNode temp = Htree[i];
  29. while (temp.parent != -1)
  30. {
  31. //限定只有前n个才是叶节点
  32. //获取字符长度
  33. Htree[i].len += 1;
  34. int parent = temp.parent;
  35. temp = Htree[parent];
  36. }
  37. //开辟编码长度对应的存储空间
  38. Htree[i].code = (char*)malloc(sizeof(char) * Htree[i].len);
  39. memset(Htree[i].code, 0, sizeof(char) * Htree[i].len);
  40. //计算编码
  41. temp = Htree[i];
  42. int index = 0;
  43. int current = i;
  44. while (temp.parent != -1) {
  45. int parent = temp.parent;
  46. int child = -1;
  47. if (Htree[parent].lchild == current) {
  48. child = 0;
  49. }
  50. else if (Htree[parent].rchild == current) {
  51. child = 1;
  52. }
  53. Htree[i].code[Htree[i].len - 1 - index] = child;//这里需要仔细思考
  54. //由于从叶子结点到根结点,因此获得的0-1序列存储要在code申请的内存空间中倒着存
  55. index++;
  56. temp = Htree[parent];
  57. current = parent;
  58. }
  59. //从HTNode的code复制到码表codeTable中
  60. codeTable[Htree[i].ch].isValid = true;
  61. codeTable[Htree[i].ch].len = Htree[i].len;
  62. codeTable[Htree[i].ch].code = (char*)malloc(sizeof(char) * Htree[i].len);
  63. memcpy(codeTable[Htree[i].ch].code, Htree[i].code, sizeof(char) * Htree[i].len);//copy
  64. }
  65. //码表写入二进制压缩文件
  66. FILE* zipfp = fopen(zipFilename,"wb");//注意是wb
  67. //先写入字符类型数
  68. fwrite(&n, sizeof(int), 1, zipfp);
  69. //再写入末尾无效编码数
  70. int invalidCount = 0;
  71. fwrite(&invalidCount, sizeof(int), 1, zipfp);
  72. //写入字符权重表
  73. fwrite(weightTable, sizeof(int), 256, zipfp);
  74. //原始文件编码写入压缩文件
  75. //重新打开fp文件
  76. fp = fopen(srcFilename, "r");
  77. char byte=0;
  78. int bitindex=0;
  79. while (!feof(fp)) {
  80. char ch = fgetc(fp);
  81. //判断拉丁文
  82. if ((int)ch < 0 ||(int) ch>=256) {
  83. continue;
  84. }
  85. HTCode hCode = codeTable[ch];
  86. //对hCode的code进行位操作
  87. for (int i = 0; i < hCode.len; i++) {
  88. if (hCode.code[i]==0) {
  89. CLR_BYTE(byte, bitindex);
  90. }
  91. else {
  92. SET_BYTE(byte, bitindex);
  93. }
  94. //判断是否读满一个字节
  95. if (bitindex == 7) {
  96. fwrite(&byte, sizeof(char), 1, zipfp);
  97. bitindex = 0;
  98. }//之所以需要判断为7是因为,实际上此时已经是满8位了
  99. else { bitindex++; }
  100. }
  101. }
  102. //读完for循环还需要考虑,是不是最终除以8有余数
  103. if (bitindex != 0)
  104. fwrite(&byte, sizeof(char), 1, zipfp);//剩余的0-1码仍然以char字节大小读入,但是标记
  105. invalidCount = 8 - (bitindex+1);//为什么-1-------因为bitindex是从0开始的,而位是从1开始的
  106. //存储一下invalidcount(这里我还没搞懂)
  107. fseek(zipfp, sizeof(int), 0);
  108. fwrite(&invalidCount, sizeof(int), 1, zipfp);
  109. fclose(fp);
  110. fclose(zipfp);
  111. //释放内存空间
  112. for (int i = 0; i < 256; i++) {
  113. if(codeTable[i].code!=nullptr)
  114. free(codeTable[i].code);
  115. }
  116. deleteHuffTree(Htree, n);
  117. return true;
  118. }

2.对已压缩文件进行解压,并且保存(huffUnzip函数)

  1. bool huffUnzip(const char* zipFilename, const char* unzipFilename) {
  2. FILE* zipfp = fopen(zipFilename, "rb");
  3. int n = 0;
  4. //读入字符种类总数
  5. fread(&n, sizeof(int),1, zipfp);
  6. //读入末尾无效位数
  7. int invalidCount = 0;
  8. fread(&invalidCount, sizeof(int), 1, zipfp);
  9. //读入权重表
  10. int weightTable2[256];
  11. fread(weightTable2, sizeof(int), 256, zipfp);
  12. //根据权重表创建新的哈夫曼树
  13. HTNode* Htree2 = createHuffTree(weightTable2, n);
  14. //开始对字符解码,存入目标文件unzipfp
  15. FILE* unzipfp = fopen(unzipFilename, "w");
  16. //找到树根位置
  17. int current = 2 * n - 1 - 1;//初始位置为HuffTree树的树根
  18. while (!feof(zipfp)) {//按照char字节读zipfp
  19. char byte;
  20. fread(&byte, sizeof(char), 1, zipfp);
  21. int len = 8;
  22. if (feof(unzipfp)) {//一直不太懂这里什么意思
  23. //到了文件末尾需要考虑无效位
  24. len = len - invalidCount;//----------------------------------
  25. }
  26. //
  27. for (int i = 0; i < len; i++) {
  28. if (GET_BYTE(byte, i) == 0) {
  29. current = Htree2[current].lchild;
  30. }
  31. else {
  32. current = Htree2[current].rchild;
  33. }
  34. if (Htree2[current].lchild == -1 && Htree2[current].rchild == -1) {
  35. //到达叶节点
  36. fprintf(unzipfp, "%c", Htree2[current].ch);
  37. current = 2 * n - 1 - 1;
  38. }
  39. }
  40. }
  41. fclose(zipfp);
  42. fclose(unzipfp);
  43. deleteHuffTree(Htree2, n);
  44. return true;
  45. }

有潜藏Bug 待修改……

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/798812
推荐阅读
相关标签
  

闽ICP备14008679号