哈夫曼编码基本练习

哈夫曼编码

#include
#include
#define MAX_WEIGHT 666
using namespace std;
int MAX = MAX_WEIGHT;
int s1 = 1,s2 = 1;

typedef struct {
    int weight;
    int number;
    int parent,lchild,rchild;
}HTNode,*HuffmanTree;


void Select(HuffmanTree &HT, int n , int *i,int *j){

    int l1 = MAX,l2 = MAX;
    for (int k = 1; k <=n; ++k) {
        if (HT[k].parent == 0 ) {
            if(HT[k].weightelse if (HT[k].weightvoid creatHuffmanCode(HuffmanTree &HT, int n){//create HuffmanTree
    if (n<1) return;
    int m = 2*n-1;
    HT = new HTNode[m+1];
    for (int i = 1; i <= m; ++i) {//inital data
        HT[i].parent = 0;
        HT[i].lchild = 0 ;
        HT[i].rchild = 0;
    }
    printf("Please enter the weight :\n");
    for (int i = 1; i <= n; ++i) {//input weight
        cin>>HT[i].weight;
    }
    for (int i = n+1; i <= m; ++i) {
        Select(HT,i - 1,&s1,&s2);
        HT[s1].parent = i;HT[s2].parent = i;
        HT[i].lchild = s1;HT[i].rchild=s2;
        HT[i].weight = HT[s1].weight + HT[s2].weight;
    }
}
int main(){
    int n;
    HuffmanTree root = NULL;
    printf("Please enter the node number:\n");
    scanf("%d",&n);
    creatHuffmanCode(root,n);
    printf("\n  number      weight     parent    lchild     rchild");
    for(int i=1;i<=2*n-1;i++)
    {
        printf("\n");
        printf("  %d   %10d  %10d %10d%10d",i,root[i].weight, root[i].parent,root[i].lchild,root[i].rchild);
    }
    return 0;

}

你可能感兴趣的:(算法练习)