建立哈夫曼树

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct
{
    int weight;
    char ch;
    int parent,lchild,rchild;
}HTNode,*HuffmanCode;

void welcome();
void HuffmanCoding(HuffmanTree&,char*,int*,int);
void select(HuffmanTree HT,int j,int *s1,int *s2);
void init();
void Coding();
void Decoding();
void Print_code();
void Print_tree();
void Read_tree(HuffmanTree&HT);
void find(HuffmanTree &HT,char*code,char*text,int i,int m);
void Convert(unsigned char T[100][100],int s,int *i,int m);
HuffmnTree HT;
int n=0;

int main()
{
    char select;
    while(1)
    {
        welcome();
        scanf("%c",&select);
        switch(select)
        {
        case 'i':
        case 'I':
            Init();break;
        case 'c':
        case 'C':
            Coding();break;
        case 'd':
        case 'D':
            Decoding();break;
        case 'p':
        case 'P':
            Print_code();break;
        case 't':
        case 'T':
            Print_tree();break;
        case 'e':
        case 'E':
            exit(1);
        default:
            printf("Input Error!");
        }
        getchar();
    }
    return 0;
}

void welcome()
{
    printf("----------------------------------\n");
    printf("      what do you want to do?     \n");
    printf("----------------------------------\n");
    printf("----------------------------------\n");
    printf("-I----Init the Huffman Tree.------\n");
    printf("-C----Code your file--------------\n");
    printf("-D----Decode the code-------------\n");
    printf("-P----Print the codefile----------\n");
    printf("-T----Print the Huffman Tree------\n");
    printf("----------------------------------\n");
}

void Init()
{
    FILE *fp;
    int i,n,w[52];
    char character[52];
    printf("\n输入字符个数n:");
    scanf("%d",&n);
    printf("输入%d个字符及其对应的权值:\n",n);
    for(i=0;i<n;i++)
    {
        char b=getchar();
        scanf("%c",&charater[i]);
        scanf("%d",&w[i]);
    }
    HuffmanCoding(HT,charater,w,n);
    if((fp=fopen("hfmtree.txt","w"))==NULL)
        printf("Open file hfmtree.txt error!\n");
    for(i=1;i<=2*n-1;i++)
    {
        if(fwrite(&HT[i],sizeof(HTNode),1,fp)!=1)
            printf("File write error!\n");
    }
    printf("\n建立哈夫曼树成功,已将其存于文件fmtree.txt中\n");
    fclose(fp);
}

void HuffmanCoding(HuffmanTree &HT,char *character,int *w,int n)
{
    int m,i,s1,s2;
    HuffmanTree p;
    if(n<=1)
        return;
    m=2*n-1;
    HT=(HuffmanTree)malloc((m+1)*sizeof(HTNode));
    for(p=HT+1,i=1;i<=n;++i,++p,++charater,++w)
    {
        p->ch=*charater;
        p->weight=*w;
        p->parent=0;
        p->lchild=0;
        p->rchild=0;
    }
    for(;i<=m;++i,++p)
    {
        p->ch=0;
        p->weight=0;
        p->parent=0;
        p->lchild=0;
        p->rchild=0;
    }
    for(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;
    }
}

void select(HuffmanTree HT,int j,int *s1,int *s2)
{
    int i;
    for(i=1;i<=j;i++)
        if(HT[i].parent==0)
    {
        *s1=i;
        break;
    }
    for(;i<=j;i++)
        if((HT[i].parent==0)&&(HT[i].parent.weight<HT[*s1].weight))
        *s1=i;
    HT[*s1].parent=1;
    for(i=1;i<=j;i++)
        if(HT[i].parent==0)
    {
        *s2=i;
        break;
    }
    for(;i<=j;i++)
        if((HT[i].parent==0)&&(i!=*s1)&&(HT[i].weight<HT[*s2].weight))
        *s2=i;
}

void Coding()
{
    FILE *fp,*fw;
    int i,  f,c,start;
    char *cd;
    HuffmanCode HC;
    if(n==0)
        n=Read_tree(HT);
    HC=(HuffmanCode)malloc((n+1)*sizeof(char*));
    cd=(char*)malloc(n*sizeof(char));
    cd[n-1]='\0';
    for(i=1;i<=n;++i)
    {
        start=n-1;
        for(c=i,f=HT[i].parent;f!=0;c=f,f=HT[f].parent)
            if(HT[f].lchild==c)
            cd[--start]='0';
        else
            cd[--start]='1';
        HC[i]=(char*)malloc(n-start)
    }
}

### 哈夫曼的构建方法(C语言实现) 哈夫曼是一种带权路径长度最短的二叉,广泛应用于数据压缩领域。在C语言中,可以通过以下步骤构建哈夫曼: #### 1. 定义哈夫曼节点结构体 首先需要定义一个结构体来表示哈夫曼的节点,包含字符、权重以及左右子节点的指针。 ```c typedef struct Node { char ch; // 字符 int freq; // 频率 struct Node *left, *right; // 左右子节点 } Node; ``` #### 2. 定义优先队列节点结构体 为了高效地选择频率最小的两个节点,通常使用优先队列(最小堆)来存储哈夫曼的节点。 ```c typedef struct QueueNode { Node *huffmanNode; // 指向哈夫曼节点的指针 struct QueueNode *next; // 下一个节点 } QueueNode; ``` #### 3. 创建节点和队列节点的函数 接下来需要实现创建哈夫曼节点和优先队列节点的函数。 ```c Node* createNode(char ch, int freq) { Node *newNode = (Node*)malloc(sizeof(Node)); newNode->ch = ch; newNode->freq = freq; newNode->left = newNode->right = NULL; return newNode; } QueueNode* createQueueNode(Node *node) { QueueNode *newQueueNode = (QueueNode*)malloc(sizeof(QueueNode)); newQueueNode->huffmanNode = node; newQueueNode->next = NULL; return newQueueNode; } ``` #### 4. 实现优先队列的操作函数 优先队列的操作包括插入节点和删除最小节点。 ```c void insertQueue(QueueNode **head, Node *node) { QueueNode *newQueueNode = createQueueNode(node); if (*head == NULL || (*head)->huffmanNode->freq > node->freq) { newQueueNode->next = *head; *head = newQueueNode; } else { QueueNode *current = *head; while (current->next != NULL && current->next->huffmanNode->freq < node->freq) { current = current->next; } newQueueNode->next = current->next; current->next = newQueueNode; } } Node* extractMin(QueueNode **head) { if (*head == NULL) return NULL; QueueNode *temp = *head; *head = (*head)->next; Node *minNode = temp->huffmanNode; free(temp); return minNode; } ``` #### 5. 构建哈夫曼 通过优先队列不断合并频率最小的两个节点,直到队列中只剩下一个节点,即为哈夫曼的根节点。 ```c Node* buildHuffmanTree(char data[], int freq[], int size) { QueueNode *head = NULL; for (int i = 0; i < size; i++) { insertQueue(&head, createNode(data[i], freq[i])); } while (head->next != NULL) { Node *left = extractMin(&head); Node *right = extractMin(&head); Node *newNode = createNode('$', left->freq + right->freq); newNode->left = left; newNode->right = right; insertQueue(&head, newNode); } return extractMin(&head); } ``` #### 6. 打印哈夫曼编码 递归遍历哈夫曼,生成并打印每个字符的哈夫曼编码。 ```c void printCodes(Node *root, int arr[], int top) { if (root->left) { arr[top] = 0; printCodes(root->left, arr, top + 1); } if (root->right) { arr[top] = 1; printCodes(root->right, arr, top + 1); } if (!root->left && !root->right) { printf("%c: ", root->ch); for (int i = 0; i < top; i++) { printf("%d", arr[i]); } printf("\n"); } } ``` #### 7. 主函数示例 最后,在主函数中调用上述函数来构建哈夫曼并打印编码。 ```c int main() { char data[] = {'a', 'b', 'c', 'd'}; int freq[] = {5, 9, 12, 13}; int size = sizeof(data) / sizeof(data[0]); Node *root = buildHuffmanTree(data, freq, size); int arr[100], top = 0; printCodes(root, arr, top); return 0; } ``` ### 注意事项 - 在实际应用中,哈夫曼的构建可以根据具体需求选择不同的构造方法,例如左小右大或先左后右。 - 解码哈夫曼编码时,通常从根节点出发,根据编码逐位判断是走左子还是右子,直到到达叶子节点为止[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值