Huffman树编码-优先队列实现
2014-11-14 21:37
295 查看
Huffman编码是之前一道算法作业题,最近又要复习考试了,先把这个的代码再看一下吧。
算法原理很简单,使用优先队列将两个节点弹出,然后合并节点之后再入队列如此循环做下去即可。
主要问题在于树的修改问题,出队的树进行修改,然后将其合并成为一个新的树,在弹出的时候,树的两个节点地址已定,但是由于循环这两个地址会进行修改,所以单独写了一个函数用来进行树的复制。
运行结果:
算法原理很简单,使用优先队列将两个节点弹出,然后合并节点之后再入队列如此循环做下去即可。
主要问题在于树的修改问题,出队的树进行修改,然后将其合并成为一个新的树,在弹出的时候,树的两个节点地址已定,但是由于循环这两个地址会进行修改,所以单独写了一个函数用来进行树的复制。
#include<iostream> #include<algorithm> #include<vector> #include<string.h> #include<queue> using namespace std; typedef struct tree{ struct tree *left; struct tree *right; int data; }Tree; struct cmp { bool operator()(const Tree &t1,const Tree &t2) { return t1.data>t2.data; } }; int a[8]={1,1,2,5,3,8,13,21};//乱序 int code[10]={0}; int m=0; void printhuffman(Tree *huffman) { if(huffman->left!=NULL) { code[m]=0;m++; printhuffman(huffman->left); m--; } if(huffman->right!=NULL) { code[m]=1;m++; printhuffman(huffman->right); m--; } if(huffman->left==NULL&&huffman->right==NULL) { printf("The code of frequency is %3d :",huffman->data); for(int i=0;i<m;i++) printf("%d ",code[i]); printf("\n"); return ; } } void copytree(Tree **a,Tree *b) { *a=new Tree(); if(b->left==NULL&&b->right==NULL) { (*a)->left=NULL;(*a)->right=NULL; (*a)->data=b->data; return; } if(b->left!=NULL) { (*a)->left=b->left; copytree(&((*a)->left),b->left); } (*a)->data=b->data; if(b->right!=NULL) { (*a)->right=b->right; copytree(&((*a)->right),b->right); } } int main() { int n=8; priority_queue<Tree,vector<Tree>,cmp> minnode; Tree huffman; for(int i=0;i<n;i++) { Tree *newtree=new Tree(); newtree->data=a[i]; newtree->left=NULL; newtree->right=NULL; minnode.push(*newtree); } while(minnode.size()>=2) { Tree temp1=minnode.top();minnode.pop(); Tree temp2=minnode.top();minnode.pop(); Tree *temp3=new Tree(); temp3->left=NULL; temp3->right=NULL; temp3->data=0; copytree(&temp3->left,&temp1); copytree(&temp3->right,&temp2); temp3->data=(*(temp3->left)).data+(*(temp3->right)).data; minnode.push(*temp3); } huffman=minnode.top(); printhuffman(&huffman); return 0; }
运行结果:
相关文章推荐
- Huffman树实现与应用(编码解码压缩解压缩)
- 利用Huffman树进行文本编码解码的实现
- huffman树的生成与编码的实现
- C++Huffman树的构造实现及编码译码过程
- Huffman树与编码的简单实现
- Huffman树及编码的实现
- Huffman树实现文件压缩编码
- Huffman树及其编码实现
- JavaScript escape/unescape编码的Java实现
- c语言实现香农编码(信息论论文)
- 利用DirectShow实现对视频文件H264编码与解码基类
- 用asp实现base64编码
- 纯编码实现Access数据库的建立或压缩
- MS-SQLServer2000中字符型数据自动编码的实现
- 最小堆应用---用最小堆实现huffman树
- 动态规划解决矩阵链乘问题的java编码实现
- JavaScript Base64编码和解码,实现URL参数传递。
- 利用ADODB.Stream实现 Bytes到String的指定编码的转换
- 使用混合脚本编程来实现的Base64编码
- Visual Basic Base64编码源码:可实现对字符串(中文)和二进制文件编码