Huffman Tree -- Huffman编码
Posted zili
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Huffman Tree -- Huffman编码相关的知识,希望对你有一定的参考价值。
#include <stdlib.h> #include <stdio.h> #include <string.h> typedef struct HuffmanTree { int weight; int parent, lchild, rchild; }HuffmanTree; typedef struct CodeNode { int ch; char bits[4+1]; }CodeNode; void SelectMin(HuffmanTree tree[], int len, int * pos1, int* pos2) { int min=255; int i, j; *pos1=0; *pos2=0; for(i=0; i<len; i++) { if(tree[i].parent==-1) if(min>tree[i].weight) { min=tree[i].weight; *pos1=i; } } min=255; for(j=0; j<len; j++) { if(j==*pos1) continue; if(tree[j].parent==-1) if(min>tree[j].weight) { min=tree[j].weight; *pos2=j; } } } void CreateHuffmanTree(HuffmanTree tree[], int n) { int m=2*n; int i; for(i=n; i<m-1; i++) { int pos1, pos2; HuffmanTree node; SelectMin(tree, i, &pos1, &pos2); printf("pos1=%d,pos2=%d ", pos1, pos2); node.weight=tree[pos1].weight+tree[pos2].weight; tree[pos1].parent=i; tree[pos2].parent=i; node.lchild=pos1; node.rchild=pos2; node.parent=-1; tree[i]=node; } } void HuffmanEncoding(HuffmanTree tree[]) { int c, p, i; int start; char cd[4+1]; cd[4]=‘ ‘; for(i=0; i<4; i++) { printf(" "); printf("%d",tree[i].weight); printf(":"); start=4; c=i; while((p=tree[c].parent)!=-1) { if(tree[p].lchild==c) { cd[--start]=‘0‘; } else { cd[--start]=‘1‘; } c=p; } printf(&cd[start]); } } int main(int argc, char* argv[]) { HuffmanTree tree[4*2]; int i, j; for(i=0; i<4; i++) { tree[i].lchild=-1; tree[i].rchild=-1; tree[i].parent=-1; } printf("请输入哈夫曼树叶子结点的权值: "); for(i=0; i<4; i++) //读入叶子结点的权值 { int weight; scanf("%d",&weight); tree[i].weight=weight; } CreateHuffmanTree(tree, 4); for(j=0; j<2*4-1; j++) { printf("tree[%d]:weight=%d ", j, tree[j].weight); } HuffmanEncoding(tree); return 0; }
以上是关于Huffman Tree -- Huffman编码的主要内容,如果未能解决你的问题,请参考以下文章