赫夫曼树的性质:
1、赫夫曼树只有前序遍历才有意义。
2、赫夫曼树的非叶子结点都是只有权重信息,而没有值的空白结点,反之,所有叶子结点都是既有权重又有值的结点。
3、结点的权重越大,结点的高度编号就是越小,离根结点就越近,前遍历访问的速度就越快,反之结点的权重越小,结点的高度编号就越大,离根结点就是越远,前序遍历访问的速度就越慢。
**赫夫曼编码:**
从赫夫曼树的根结点出发进行前序遍历,遍历过程中把往左子树遍历记作0,把往右子树遍历记作1,到达叶子结点时,走过的路径所形成的01信息被称为赫夫曼编码,使用这种编码就访问到赫夫曼树根结点出发访问到叶子结点中的数据。
这种编码的特点就是权重越大的数据,生成的编码就越短,权重越小的数据,生成的编码就越长。
这种编码可以用于提高数据传输效率,还有文件的压缩和解压。
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>
#include <unistd.h>
#include <math.h>
#include "heap.h"
typedef struct CharCode
{
uint32_t code; // 赫夫曼编码
uint8_t cnt; // 编码位数
} CharCode;
// 赫夫曼编码数组
CharCode code_arr[128];
// 赫夫曼树结点
typedef struct TreeNode
{
uint8_t data; // 数据
uint32_t weight; // 权重
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 用于比较结点权重的回调函数,给小堆根使用的
int node_cmp(const void *p1, const void *p2)
{
if (((TreeNode *)p1)->weight > ((TreeNode *)p2)->weight)
return 1;
if (((TreeNode *)p1)->weight < ((TreeNode *)p2)->weight)
return -1;
return 0;
}
TreeNode *create_node(char data, size_t weight)
{
TreeNode *node = malloc(sizeof(TreeNode));
node->data = data;
node->weight = weight;
node->left = NULL;
node->right = NULL;
return node;
}
void _create_code(TreeNode *root, uint8_t path, uint32_t code, uint8_t cnt)
{
if (NULL == root)
return;
code = (code << 1) + path;
// 到达叶子结点时,记录赫夫曼编码
if (0 != root->data)
{
code_arr[root->data].code = code;
code_arr[root->data].cnt = cnt;
return;
}
_create_code(root->left, 0, code, cnt + 1);
_create_code(root->right, 1, code, cnt + 1);
}