哈夫曼树原理及其C语言实现

目录

原理

应用场景

实现步骤

C语言实现

总结


原理

哈夫曼树(Huffman Tree),又称最优二叉树,是一种带权路径长度最短的二叉树,广泛应用于数据压缩领域。所谓树的带权路径长度,是指树中所有的叶结点的权值乘上其到根结点的路径长度(若根结点为第0层,叶结点到根结点的路径长度为叶结点的层数)之和。它的核心思想是:权值越大的节点离根越近,权值越小的节点离根越远,从而最小化整体的带权路径长度(WPL)。

关键概念:

  1. 权值(Weight):节点的权重(如字符出现的频率)。

  2. 路径长度:从根节点到某节点的边数。

  3. 带权路径长度(WPL):所有叶子节点的权值 × 路径长度之和。

哈夫曼树的构造基于贪心算法,具体步骤如下:

  1. 初始状态:给定N个权值,将它们视为N棵仅含一个结点的树(森林)。
  2. 选择合并:在森林中选出两个根结点权值最小的树,将它们合并为一棵新树,新树的根结点权值为这两个子树根结点权值之和。
  3. 更新森林:从森林中删除这两个最小的树,并将新树加入森林。
  4. 重复操作:重复步骤2和3,直到森林中只剩下一棵树,这棵树即为所求得的哈夫曼树。

以下是一个简单的哈夫曼树构造过程的图形化展示(假设初始权值为2, 3, 6, 8, 9):

  • 初始状态:五棵独立的树,每棵树的权值分别为2, 3, 6, 8, 9。
  • 第一次合并:选择权值最小的两棵树(权值为2和3),合并成新树,新树的权值为5。
  • 第二次合并:再次选择权值最小的两棵树(此时为权值为5和6的树),合并成新树,新树的权值为11。
  • 后续合并:继续上述过程,直到所有树合并为一棵哈夫曼树。

示例:假设字符集 {A, B, C, D} 的权值分别为 {5, 2, 1, 3},哈夫曼树构建过程如下:

Step 1: 最小权值 C(1) 和 B(2) → 合并为权值3的父节点
Step 2: 新节点3 和 D(3) → 合并为权值6的父节点
Step 3: 合并 A(5) 和 6 → 最终根节点权值11

最终哈夫曼树:
       11
      /  \
     5    6
         / \
        3   3
       / \ 
      1   2 (B)
   (C)

应用场景

  1. 数据压缩:哈夫曼编码(Huffman Coding)将高频字符用短编码,低频字符用长编码。

  2. 文件压缩工具:如 ZIP、GZIP 使用哈夫曼算法。

  3. 图像压缩:JPEG 格式中的熵编码阶段。

  4. 通信协议:优化数据传输效率。

实现步骤

哈夫曼树的实现步骤:

  1. 统计字符频率:遍历数据,统计每个字符的出现次数作为权值。

  2. 构建最小堆:将所有字符节点按权值排序,形成优先队列(最小堆)。

  3. 合并节点:循环取出权值最小的两个节点,合并为新节点,放回堆中。

  4. 生成编码表:从根节点出发,向左为0,向右为1,记录叶子节点的路径编码。

  5. 压缩与解压:根据编码表将原始数据转换为二进制流,或反向解码。

C语言实现

1. 定义哈夫曼树节点结构

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_TREE_NODES 256

typedef struct HuffmanNode {
    char ch;                // 字符(叶子节点有效)
    int weight;             // 权值(字符频率)
    struct HuffmanNode *left, *right; // 左右子节点
} HuffmanNode;

typedef struct PriorityQueue {
    HuffmanNode **nodes;    // 节点指针数组
    int size;               // 当前堆大小
    int capacity;           // 堆容量
} PriorityQueue;

2. 构建最小堆(优先队列)

// 初始化优先队列
PriorityQueue* createQueue(int capacity) {
    PriorityQueue* queue = (PriorityQueue*)malloc(sizeof(PriorityQueue));
    queue->nodes = (HuffmanNode**)malloc(capacity * sizeof(HuffmanNode*));
    queue->size = 0;
    queue->capacity = capacity;
    return queue;
}

// 上浮调整(插入节点时保持最小堆性质)
void heapifyUp(PriorityQueue* queue, int index) {
    int parent = (index - 1) / 2;
    while (index > 0 && queue->nodes[index]->weight < queue->nodes[parent]->weight) {
        HuffmanNode* temp = queue->nodes[index];
        queue->nodes[index] = queue->nodes[parent];
        queue->nodes[parent] = temp;
        index = parent;
        parent = (index - 1) / 2;
    }
}

// 下沉调整(删除节点时保持最小堆性质)
void heapifyDown(PriorityQueue* queue, int index) {
    int left = 2 * index + 1;
    int right = 2 * index + 2;
    int smallest = index;
    if (left < queue->size && queue->nodes[left]->weight < queue->nodes[smallest]->weight) {
        smallest = left;
    }
    if (right < queue->size && queue->nodes[right]->weight < queue->nodes[smallest]->weight) {
        smallest = right;
    }
    if (smallest != index) {
        HuffmanNode* temp = queue->nodes[index];
        queue->nodes[index] = queue->nodes[smallest];
        queue->nodes[smallest] = temp;
        heapifyDown(queue, smallest);
    }
}

// 插入节点
void enqueue(PriorityQueue* queue, HuffmanNode* node) {
    if (queue->size >= queue->capacity) return;
    queue->nodes[queue->size] = node;
    heapifyUp(queue, queue->size);
    queue->size++;
}

// 取出权值最小的节点
HuffmanNode* dequeue(PriorityQueue* queue) {
    if (queue->size == 0) return NULL;
    HuffmanNode* minNode = queue->nodes[0];
    queue->nodes[0] = queue->nodes[queue->size - 1];
    queue->size--;
    heapifyDown(queue, 0);
    return minNode;
}

3. 构建哈夫曼树

// 创建叶子节点
HuffmanNode* createLeafNode(char ch, int weight) {
    HuffmanNode* node = (HuffmanNode*)malloc(sizeof(HuffmanNode));
    node->ch = ch;
    node->weight = weight;
    node->left = node->right = NULL;
    return node;
}

// 构建哈夫曼树
HuffmanNode* buildHuffmanTree(char data[], int weights[], int n) {
    PriorityQueue* queue = createQueue(MAX_TREE_NODES);
    for (int i = 0; i < n; i++) {
        HuffmanNode* node = createLeafNode(data[i], weights[i]);
        enqueue(queue, node);
    }
    while (queue->size > 1) {
        HuffmanNode* left = dequeue(queue);
        HuffmanNode* right = dequeue(queue);
        HuffmanNode* parent = (HuffmanNode*)malloc(sizeof(HuffmanNode));
        parent->ch = '\0';  // 内部节点无字符
        parent->weight = left->weight + right->weight;
        parent->left = left;
        parent->right = right;
        enqueue(queue, parent);
    }
    HuffmanNode* root = dequeue(queue);
    free(queue->nodes);
    free(queue);
    return root;
}

4. 生成哈夫曼编码表

void generateCodes(HuffmanNode* root, char* code, int depth, char** codes) {
    if (root == NULL) return;
    if (root->left == NULL && root->right == NULL) { // 叶子节点
        code[depth] = '\0';
        codes[(unsigned char)root->ch] = strdup(code);
        return;
    }
    code[depth] = '0';
    generateCodes(root->left, code, depth + 1, codes);
    code[depth] = '1';
    generateCodes(root->right, code, depth + 1, codes);
}

5. 压缩与解压示例

// 压缩函数(将字符串转换为哈夫曼编码)
char* compress(char* input, char** codes) {
    int len = strlen(input);
    char* compressed = (char*)malloc(MAX_TREE_NODES * len);
    compressed[0] = '\0';
    for (int i = 0; i < len; i++) {
        strcat(compressed, codes[(unsigned char)input[i]]);
    }
    return compressed;
}

// 解压函数(根据哈夫曼树解码)
void decompress(HuffmanNode* root, char* compressed) {
    HuffmanNode* current = root;
    int len = strlen(compressed);
    for (int i = 0; i < len; i++) {
        if (compressed[i] == '0') {
            current = current->left;
        } else {
            current = current->right;
        }
        if (current->left == NULL && current->right == NULL) {
            printf("%c", current->ch);
            current = root; // 重置到根节点继续解码
        }
    }
}

6. 测试代码

int main() {
    char data[] = {'A', 'B', 'C', 'D'};
    int weights[] = {5, 2, 1, 3};
    int n = sizeof(data) / sizeof(data[0]);

    // 构建哈夫曼树
    HuffmanNode* root = buildHuffmanTree(data, weights, n);

    // 生成编码表
    char* codes[MAX_TREE_NODES] = {NULL};
    char code[MAX_TREE_NODES];
    generateCodes(root, code, 0, codes);

    // 打印编码
    printf("哈夫曼编码表:\n");
    for (int i = 0; i < MAX_TREE_NODES; i++) {
        if (codes[i] != NULL) {
            printf("%c: %s\n", (char)i, codes[i]);
        }
    }

    // 压缩示例
    char* input = "ABACAD";
    char* compressed = compress(input, codes);
    printf("\n原始数据: %s\n压缩后的二进制: %s\n", input, compressed);

    // 解压示例
    printf("解压结果: ");
    decompress(root, compressed);
    printf("\n");

    // 释放内存(略)
    return 0;
}

输出示例

哈夫曼编码表:
A: 0
B: 110
C: 111
D: 10

原始数据: ABACAD
压缩后的二进制: 01100111010
解压结果: ABACAD

总结

  • 优点:哈夫曼编码是无损压缩,保证数据完整性。

  • 缺点:需存储编码表,压缩率依赖字符频率分布。

  • 优化方向:动态哈夫曼编码(适应数据变化)、结合其他算法(如LZ77)。

#include #include #include #include using namespace std; # define MaxN 100//初始设定的最大结点数 # define MaxC 1000//最大编码长度 # define ImpossibleWeight 10000//结点不可能达到的权值 # define n 26//字符集的个数 //-----------哈夫曼的结点结构类型定义----------- typedef struct //定义哈夫曼各结点 { int weight;//权值 int parent;//双亲结点下标 int lchild;//左孩子结点下标 int rchild;//右孩子结点下标 }HTNode,*HuffmanTree;//动态分配数组存储哈夫曼 typedef char**HuffmanCode;//动态分配数组存储哈夫曼编码表 //-------全局变量-------- HuffmanTree HT; HuffmanCode HC; int *w;//权值数组 //const int n=26;//字符集的个数 char *info;//字符值数组 int flag=0;//初始化标记 //********************************************************************** //初始化函数 //函数功能: 从终端读入字符集大小n , 以及n个字符和n个权值,建立哈夫曼,并将它存于文件hfmTree中 //函数参数: //向量HT的前n个分量表示叶子结点,最后一个分量表示根结点,各字符的编码长度不等,所以按实际长度动态分配空间 void Select(HuffmanTree t,int i,int &s1,int &s2) { //s1为最小的两个值中序号最小的那个 int j; int k=ImpossibleWeight;//k的初值为不可能达到的最大权值 for(j=1;j<=i;j++) { if(t[j].weight<k&&t[j].parent==0) {k=t[j].weight; s1=j;} } t[s1].parent=1; k=ImpossibleWeight; for(j=1;j<=i;j++) { if(t[j].weight0),构造哈夫曼HT,并求出n个字符的哈弗曼编码HC { int i,m,c,s1,s2,start,f; HuffmanTree p; char* cd; if(num<=1) return; m=2*num-1;//m为结点数,一棵有n个叶子结点的哈夫曼共有2n-1个结点,可以存储在一个大小为2n-1的一维数组中 HT=(HuffmanTree)malloc((m+1)*sizeof(HTNode));//0号单元未用 //--------初始化哈弗曼------- for(p=HT+1,i=1;iweight=*w; p->parent=0; p->lchild=0; p->rchild=0; } for(i=num+1;iweight=0; p->parent=0; p->lchild=0; p->rchild=0; } //--------建哈夫曼------------- for(i=num+1;i<=m;i++) { Select(HT,i-1,s1,s2);//在HT[1...i-1]选择parent为0且weight最小的两个结点,其序号分别为s1和s2 HT[s1].parent=i; HT[s2].parent=i; HT[i].lchild=s1; HT[i].rchild=s2;//左孩子权值小,右孩子权值大 HT[i].weight=HT[s1].weight+HT[s2].weight; } //-------从叶子到根逆向求每个字符的哈弗曼编码-------- HC=(HuffmanCode)malloc((num+1)*sizeof(char *));//指针数组:分配n个字符编码的头指针向量 cd=(char*)malloc(n*sizeof(char*));//分配求编码的工作空间 cd[n-1]='\0';//编码结束符 for(i=1;i<=n;i++)//逐个字符求哈弗曼编码 { start=n-1;//编码结束符位置 for(c=i,f=HT[i].parent;f!=0;c=f,f=HT[f].parent)//从叶子到跟逆向求哈弗曼编码 if(HT[f].lchild==c) cd[--start]='0';//判断是左孩子还是右孩子(左为0右为1) else cd[--start]='1'; HC[i]=(char*)malloc((num-start)*sizeof(char*));//按所需长度分配空间 int j,h; strcpy(HC[i],&cd[start]); } free(cd); } //****************初始化函数****************** void Initialization() { flag=1;//标记为已初始化 int i; w=(int*)malloc(n*sizeof(int));//为26个字符权值分配空间 info=(char*)malloc(n*sizeof(char));//为26个字符分配空间 ifstream infile("ABC.txt",ios::in); if(!infile) { cerr<<"打开失败"<<endl; exit(1); } for(i=0;i>info[i]; infile>>w[i]; } infile.close(); cout<<"读入字符成功!"<<endl; HuffmanCoding(HT,HC,w,n); //------------打印编码----------- cout<<"依次显示各个字符的值,权值或频度,编码如下"<<endl; cout<<"字符"<<setw(6)<<"权值"<<setw(11)<<"编码"<<endl; for(i=0;i<n;i++) { cout<<setw(3)<<info[i]; cout<<setw(6)<<w[i]<<setw(12)<<HC[i+1]<<endl; } //---------将建好的哈夫曼写入文件------------ cout<<"下面将哈夫曼写入文件"<<endl; ofstream outfile("hfmTree.txt",ios::out); if(!outfile) { cerr<<"打开失败"<<endl; exit(1); } for(i=0;i<n;i++,w++) { outfile<<info[i]<<" "; outfile<<w[i]<<" "; outfile<<HC[i+1]<<" "; } outfile.close(); cout<<"已经将字符与对应的权值,编码写入根目录下文件hfmTree.txt"<<endl; } //*****************输入待编码字符函数************************* void Input() { char string[100]; ofstream outfile("ToBeTran.txt",ios::out); if(!outfile) { cerr<<"打开失败"<<endl; exit(1); } cout<<"请输入你想要编码的字符串(字符个数应小于100),以#结束"<>string; for(int i=0;string[i]!='\0';i++) { if(string[i]=='\0') break; outfile<<string[i]; } cout<<"获取报文成功"<<endl; outfile.close(); cout<<"------"<<"已经将报文存入根目录下的ToBeTran.txt文件"<<endl; } //******************编码函数**************** void Encoding() { int i,j; char*string; string=(char*)malloc(MaxN*sizeof(char)); cout<<"下面对根目录下的ToBeTran.txt文件中的字符进行编码"<<endl; ifstream infile("ToBeTran.txt",ios::in); if(!infile) { cerr<<"打开失败"<<endl; exit(1); } for(i=0;i>string[i]; } for(i=0;i<100;i++) if(string[i]!='#') cout<<string[i]; else break; infile.close(); ofstream outfile("CodeFile.txt",ios::out); if(!outfile) { cerr<<"打开失败"<<endl; exit(1); } for(i=0;string[i]!='#';i++) { for(j=0;j<n;j++) { if(string[i]==info[j]) outfile<<HC[j+1]; } } outfile<<'#'; outfile.close(); free(string); cout<<"编码完成------"; cout<<"编码已写入根目录下的文件CodeFile.txt中"<<endl; } //******************译码函数**************** void Decoding() { int j=0,i; char *code; code=(char*)malloc(MaxC*sizeof(char)); char*string; string=(char*)malloc(MaxN*sizeof(char)); cout<<"下面对根目录下的CodeFile.txt文件中的代码进行译码"<<endl; ifstream infile("CodeFile.txt",ios::in); if(!infile) { cerr<<"打开失败"<<endl; exit(1); } for( i=0;i>code[i]; if(code[i]!='#') { cout<<code[i]; } else break; } infile.close(); int m=2*n-1; for(i=0;code[i-1]!='#';i++) { if(HT[m].lchild==0) { string[j]=info[m-1]; j++; m=2*n-1; i--; } else if(code[i]=='1') m=HT[m].rchild; else if(code[i]=='0') m=HT[m].lchild; } string[j]='#'; ofstream outfile("TextFile.txt",ios::out); if(!outfile) { cerr<<"打开失败"<<endl; exit(1); } cout<<"的译码为------"<<endl; for( i=0;string[i]!='#';i++) { outfile<<string[i]; cout<<string[i]; } outfile<<'#'; outfile.close(); cout<<"------译码完成------"<<endl; cout<<"译码结果已写入根目录下的文件TextFile.txt中"<<endl; free(code); free(string); } //*************打印编码函数**************** void Code_printing() { int i; char *code; code=(char*)malloc(MaxC*sizeof(char)); cout<<"下面打印根目录下文件CodeFile.txt中的编码"<<endl; ifstream infile("CodeFile.txt",ios::in); if(!infile) { cerr<<"打开失败"<<endl; exit(1); } for( i=0;i>code[i]; if(code[i]!='#') cout<<code[i]; else break; } infile.close(); cout<<endl; ofstream outfile("CodePrin.txt",ios::out); if(!outfile) { cerr<<"打开失败"<<endl; exit(1); } for(i=0;code[i]!='#';i++) { outfile<<code[i]; } outfile.close(); free(code); cout<<"------打印结束------"<<endl; cout<<"该字符形式的编码文件已写入文件CodePrin.txt中"<<endl; } //*************打印哈夫曼函数**************** int numb=0; void coprint(HuffmanTree start,HuffmanTree HT) //start=ht+26这是一个递归算法 { if(start!=HT) { ofstream outfile("TreePrint.txt",ios::out); if(!outfile) { cerr<<"打开失败"<rchild,HT); //递归先序遍历 cout<<setw(5*numb)<weight<rchild==0) cout<<info[start-HT-1]<<endl; outfile<weight; coprint(HT+start->lchild,HT); numb--; outfile.close(); } } void Tree_printing(HuffmanTree HT,int num) { HuffmanTree p; p=HT+2*num-1; //p=HT+26 cout<<"下面打印赫夫曼"<<endl; coprint(p,HT); //p=HT+26 cout<<"打印工作结束"<<endl; } //*************主函数************************** int main() { char choice; do{ cout<<"************哈弗曼编/译码器系统***************"<<endl; cout<<"请选择您所需功能:"<<endl; cout<<":初始化哈弗曼"<<endl; cout<<":输入待编码字符串"<<endl; cout<<":利用已建好的哈夫曼进行编码"<<endl; cout<<":利用已建好的哈夫曼进行译码"<<endl; cout<<":打印代码文件"<<endl; cout<<":打印哈夫曼"<<endl; cout<<":退出"<<endl; if(flag==0) { cout<<"请先初始化哈夫曼,输入I"<<endl; cout<<""<>choice; switch(choice) { case 'I':Initialization();break; case 'W':Input();break; case 'E':Encoding();break; case 'D':Decoding();break; case 'P':Code_printing();break; case 'T':Tree_printing(HT,n);break; case 'Q':;break; default:cout<<"输入的命令出错,请重新输入!"<<endl; } }while(choice!='Q'); free(w); free(info); free(HT); free(HC); system("pause"); return 0; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

W说编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值