C语言创建哈夫曼树和哈夫曼编码

#include 
#include 
#include 

#define N 20
#define M 2*N-1

typedef struct {
    int weight;
    int parent;
    int lchild;
    int rchild;
} HTNode, HuffmanTree[M + 1];

void Select(HuffmanTree ht, int m, int *s1, int *s2) {

    int min1 = 1000;
    int min2 = 1000;
//    for (int j = 1; j <= m; ++j) {
//        printf("%d ",ht[j].weight);
//    }
    //printf("\n");
    for (int i = 1; i <= m; i++) {
        if (ht[i].parent == 0 && min1 > ht[i].weight) {
            min1 = ht[i].weight;
            *s1 = i;
        }
    }
    for (int i = 1; i <= m; i++) {
        if (i != (*s1) && ht[i].parent == 0) {
            if (ht[i].weight < min2) {
                min2 = ht[i].weight;
                *s2 = i;
            }
        }
    }
    printf("min1=%d,min2=%d\n", min1, min2);
}

//构造哈夫曼树
void createHFTree(HuffmanTree ht, int w[], int n) {
    int i, m;
    int s1, s2;
    for (i = 1; i <= n; i++) {
        ht[i].weight = w[i];
        ht[i].parent = 0;
        ht[i].lchild = 0;
        ht[i].rchild = 0;
    }
    m = 2 * n - 1;
    for (i = n + 1; i <= m; i++) {
        ht[i].weight = 0;
        ht[i].parent = 0;
        ht[i].lchild = 0;
        ht[i].rchild = 0;
    }
    for (i = n + 1; i <= m; i++) {
        Select(ht, i - 1, &s1, &s2);
        ht[i].weight = ht[s1].weight + ht[s2].weight;
        ht[s1].parent = i;
        ht[s2].parent = i;
        ht[i].lchild = s1;
        ht[i].rchild = s2;
    }
}

//编码
char *createHFCode(HuffmanTree ht, char **hc, int n) {
    char *cd;
    int start, i;
    hc = (char *) malloc(sizeof(char *) * (n + 1));
    cd = (char *) malloc(n * sizeof(char));
    cd[n - 1] = '\0';
    for (i = 1; i <= n; ++i) {
        start = n - 1;
        int c = i;
        int p = ht[i].parent;
        while (p != 0) {
            if (ht[p].lchild == c)
                cd[--start] = '0';
            else
                cd[--start] = '1';
            c = p;
            p = ht[p].parent;
        }
        hc[i] = (char *) malloc((n - start) * sizeof(char));
        //puts(cd);
        strcpy(hc[i], &cd[start]);
        //puts(hc[i]);
    }
    free(cd);
//    printf("The Code is:\n");
//    for (i = 1; i <= n; i++) {
//        printf("%d:%s\n", ht[i].weight, hc[i]);
//    }
    return hc;
}

int main() {
    HuffmanTree ht;
    char **hc = NULL;
    int n, i, a[100];
    scanf("%d", &n);
    for (i = 1; i <= n; i++) {
        scanf("%d", &a[i]);
    }
    createHFTree(ht, a, n);

    int m = 2 * n - 1;
    printf("HuffmanTree is:\n");
    for (i = 1; i <= m; i++) {
        printf("%d:%d %d %d %d\n", i, ht[i].weight, ht[i].parent, ht[i].lchild, ht[i].rchild);
    }
    hc = createHFCode(ht, hc, n);
    printf("The Code is:\n");
    for (i = 1; i <= n; i++) {
        printf("%d:%s\n", ht[i].weight, hc[i]);
    }
    return 0;
}

你可能感兴趣的:(c语言,哈夫曼树)