哈夫曼树的构建—数据结构算法

部分源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define M 8
typedef struct{
char data;
int weight;
int parent,lchlid,rchlid;
}HTNode,*HuffmanTree;
 
 
int InitHTNode(HuffmanTree &HT,char da[],int w[]);
int CreateTree(HuffmanTree &HT);
int Select(HuffmanTree &HT,int& index,int cout);
int CodeTree(HuffmanTree &HT,char code[][M]);
int DeCodeTree(HuffmanTree &HT,char decode[]);
 
  
 
int InitHTNode(HuffmanTree &HT,char da[],int w[]){
int l=strlen(da);
int m=2*l;
HT=new HTNode[m];
for(int i=1;i<m;i++){
if(i<=l){
HT[i].data=da[i-1];
HT[i].weight=w[i-1];
HT[i].parent=0;
HT[i].lchlid=0;
HT[i].rchlid=0;
}else{
HT[i].data=' ';
HT[i].weight=0;
HT[i].parent=0;
HT[i].lchlid=0;
HT[i].rchlid=0;
}
}
}
 
int CreateTree(HuffmanTree &HT){
int index;
int cout;
for(int i=M+1;i<2*M;i++){
cout=i;
Select(HT,index,cout);//left
HT[i].lchlid=index;
HT[index].parent=i;
HT[i].weight+=HT[index].weight;
Select(HT,index,cout);//right
HT[i].rchlid=index;
HT[index].parent=i;
HT[i].weight+=HT[index].weight;
}
}
 
int Select(HuffmanTree &HT,int& index,int cout){
int w=100;
for(int i=1;i<cout;i++){
if(HT[i].parent==0 && HT[i].weight!=0){
if(HT[i].weight<w){
index=i;
w=HT[i].weight;
}
}
}
}
 
int CodeTree(HuffmanTree &HT,char code[][M]){
int p,c;
for(int i=1;i<=M;i++){
p=HT[i].parent;
c=i;
int cout=0;
while(p!=0){
if(HT[p].lchlid==c){
code[i-1][cout]='0';
}
if(HT[p].rchlid==c){
code[i-1][cout]='1';
}
c=p;
p=HT[p].parent;
cout++;
}
 
}
}
 
int DeCodeTree(HuffmanTree &HT,char decode[]){
int l=strlen(decode);
int index=2*M-1;
for(int i=0;i<l;i++){
if(decode[i]=='0'){
index=HT[index].lchlid;
if(HT[index].lchlid==0&&HT[index].rchlid==0){
printf("%c",HT[index].data);
index=2*M-1;
}
}
else{
index=HT[index].rchlid;
if(HT[index].lchlid==0&&HT[index].rchlid==0){
printf("%c",HT[index].data);
index=2*M-1;
}
}
}
};

  

注意这里仅为部分代码。没有main主函数 获取源码请关注“值南针”微信公众号:可用电脑微信关注或手机关注(要最新版微信pc端)。在电脑方便。直接下载源码。

 

 

 

点击想要的算法

点击下载直接就可以用的。

posted @   值南针  阅读(607)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示