哈夫曼树及哈夫曼编码

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

哈夫曼树及哈夫曼编码

#include

using namespace std;

#define MAXVALUE 16

const int n=4;

typedef struct{

int weight;

int parent;

int lchild;

int rchild;

}HNodeType;

void Creat_HuffMTree(HNodeType HFMTree[],int n){ //构造的哈夫曼树存贮于HFMTree[],n为叶子节点的个数

int m1,x1,m2,x2;//x1,x2存放其最小权值和次小权值m1,m2存储其位置

int i,j;

for(i=0;i<2*n-1;i++){//哈夫曼树初始化

HFMTree[i].weight=0;

HFMTree[i].parent=-1;

HFMTree[i].lchild=-1;

HFMTree[i].rchild=-1;

}

for(i=0;i

cout<<"请输入第"<

cin>>HFMTree[i].weight;}//输入n个叶子结点的权值

for(i=0;i

x1=x2=MAXVALUE;

m1=m2=0;

for(j=0;j

if(HFMTree[j].parent==-1&&HFMTree[j].weight

x2=x1;//存放数组下标

m2=m1;

x1=HFMTree[j].weight;

m1=j;

}

else if(HFMTree[j].parent==-1&&HFMTree[j].weight

x2=HFMTree[j].weight;

m2=j;

}

}//将两棵子树合并为一棵子树

HFMTree[m1].parent=n+i;

HFMTree[m2].parent=n+i;

HFMTree[n+i].weight=HFMTree[m1].weight+HFMTree[m2].weight;

HFMTree[n+i].lchild=m1;

HFMTree[n+i].rchild=m2;

}

cout<<"哈夫曼树为:"<

for(i=0;i<2*n-1;i++){

cout<

}

}

typedef struct{

int bit[n];

int start;

}HCodeType;

void HuffmanCode(HNodeType HFMTree[],HCodeType HuffCode[]){ HCodeType cd;

int i,j,c,p;

for(i=0;i

cd.start=n-1;

c=i;

p=HFMTree[c].parent;

while(p!=-1){

if(HFMTree[p].lchild==c)

cd.bit[cd.start]=0;

else cd.bit[cd.start]=1;

cd.start--;

c=p;

p=HFMTree[c].parent;

}

cout<<"第"<

for(j=cd.start+1;j

//HuffCode[i].bit[j]=cd.bit[j];

//cout<

cout<

}

HuffCode[i].start=cd.start+1;

cout<

cout<<"起始位置:"<

}

}

int main(){

HNodeType HFMTree[7];//2*n-1

Creat_HuffMTree(HFMTree,n);

HCodeType HuffCode[4];

HuffmanCode(HFMTree,HuffCode);

return 0;

}

相关文档
最新文档