您的位置:首页 > 其它

创建哈佛曼树并求出哈弗曼编码

2015-11-18 13:20 302 查看
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;

struct hTNode{
unsigned int weight;
unsigned int parent,lchild,rchild;
};

typedef hTNode* huffTree;
//定义一个双重指针来存放Huffman编码
typedef char** huffCode;
//树上所有结点的个数
int cnt,i;

/**
* 选择权值最小的两个结点
* tree: 哈弗曼树
* n: 哈弗曼树上结点的个数
* s1,s2: 选出来的结果 ,即在树上的位置
*/
void select(huffTree tree, int n, int &s1, int &s2)
{
int i;
for(i = 2; i <= n; i ++)
{
if(tree[s1].parent != 0)
{
s1 = i;
continue;
}
if(tree[i].parent == 0)
if(tree[i].weight < tree[s1].weight)
s1 = i ;
}
for(i = 1; i <= n; i ++)
{
if(i == s1) continue;
if(s2 == s1 || tree[s2].parent != 0)
{
s2 = i;
continue;
}
if(tree[i].parent == 0)
if(s1 != s2 && tree[i].weight < tree[s2].weight)
s2 = i ;
}
}

/**
* 这个函数是本程序的最主要的函数,用来建立哈弗曼树,同时生成哈弗曼编码。
* n: 输入的数据的个数
* weight: 每个节点的权值
* tree: 哈弗曼树
* code: 哈弗曼编码
*/
void HuffEncoding(int n, int* weight, huffTree &tree, huffCode &codes)
{
int s1=1, s2=2;
huffTree p;
//如果输入的数据个数小于2,那么直接返回
if(n < 2) return;
cnt = 2*n - 1;

//申请这棵哈弗曼树的内存空间
tree = (huffTree)malloc((cnt+1)*sizeof(hTNode));
//把每一个录入的数据建成结点(或者说小树)
for(p = tree+1,i = 1; i <= n; ++i, ++p, ++weight)
{
p->weight = *weight;
p->lchild = 0;
p->rchild = 0;
p->parent = 0;
}
//初始化哈弗曼树上的每一个结点,先都设成0
for(;i <= cnt; ++i, ++p)
{
p->weight = 0;
p->lchild = 0;
p->rchild = 0;
p->parent = 0;
}
//开始建立哈弗曼树
for(i = n + 1; i <= cnt; ++ i)
{
select(tree, i-1, s1, s2);
tree[s1].parent = i;
tree[s2].parent = i;
tree[i].lchild = s1;
tree[i].rchild = s2;
tree[i].weight = tree[s1].weight + tree[s2].weight;
}
//开始求各个叶子结点的Huffman编码
{
char* cd;
int start,c,f=0;
codes = (huffCode)malloc((n+1)*sizeof(char*));
cd = (char*)malloc((n+1)*sizeof(char));
cd[n-1]='/0';
for(i = 1; i <= n; ++i)
{
start = n - 1;
for(c = i,f = tree[i].parent; f != 0;
c = f, f = tree[f].parent)
if(tree[f].lchild == c) cd[--start] = '0';
else cd[--start] = '1';
codes[i] = (char*)malloc((n - start)*sizeof(char));
strcpy(codes[i],&cd[start]);
}
free(cd);
}

}//HuffEncoding

int main()
{
int nn;
int* weight;
huffTree tree;
huffCode codes;
printf("请输入结点的个数:");
scanf("%d",&nn);
printf("\n");
weight = (int*)malloc(nn*sizeof(int));
printf("请输入各个结点的权值:");
for(i = 0; i < nn; i ++)
{
scanf("%d",&weight[i]);
}
printf("\n");
HuffEncoding(nn,weight,tree,codes);
printf("各个结点的哈弗曼编码如下:\n");
printf("\n");
for(i = 1; i <= nn; i ++)
{
printf("结点%d的哈弗曼编码为:%s\n",tree[i].weight,codes[i]);
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: