帮我用C语言写一个按前序遍历方法输出哈夫曼编码的函数
时间: 2023-06-20 09:06:07 浏览: 108
使用c语言实现哈夫曼编码
好的,以下是一个简单的按前序遍历输出哈夫曼编码的函数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
char ch;
int freq;
struct node *left, *right;
} Node;
typedef struct {
int size;
int capacity;
Node **arr;
} Heap;
Node *newNode(char ch, int freq) {
Node *node = (Node *)malloc(sizeof(Node));
node->ch = ch;
node->freq = freq;
node->left = node->right = NULL;
return node;
}
Heap *newHeap(int capacity) {
Heap *heap = (Heap *)malloc(sizeof(Heap));
heap->size = 0;
heap->capacity = capacity;
heap->arr = (Node **)malloc(capacity * sizeof(Node *));
return heap;
}
void swap(Node **a, Node **b) {
Node *temp = *a;
*a = *b;
*b = temp;
}
void heapify(Heap *heap, int i) {
int smallest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < heap->size && heap->arr[left]->freq < heap->arr[smallest]->freq) {
smallest = left;
}
if (right < heap->size && heap->arr[right]->freq < heap->arr[smallest]->freq) {
smallest = right;
}
if (smallest != i) {
swap(&heap->arr[i], &heap->arr[smallest]);
heapify(heap, smallest);
}
}
void insertHeap(Heap *heap, Node *node) {
if (heap->size == heap->capacity) {
return;
}
int i = heap->size;
heap->arr[i] = node;
heap->size++;
while (i > 0 && heap->arr[(i - 1) / 2]->freq > heap->arr[i]->freq) {
swap(&heap->arr[i], &heap->arr[(i - 1) / 2]);
i = (i - 1) / 2;
}
}
Node *extractMin(Heap *heap) {
if (heap->size == 0) {
return NULL;
}
Node *min = heap->arr[0];
heap->arr[0] = heap->arr[heap->size - 1];
heap->size--;
heapify(heap, 0);
return min;
}
void buildHeap(Heap *heap) {
int n = heap->size;
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(heap, i);
}
}
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");
}
}
void huffmanCodes(char data[], int freq[], int size) {
Heap *heap = newHeap(size);
for (int i = 0; i < size; i++) {
Node *node = newNode(data[i], freq[i]);
insertHeap(heap, node);
}
while (heap->size > 1) {
Node *left = extractMin(heap);
Node *right = extractMin(heap);
Node *parent = newNode('$', left->freq + right->freq);
parent->left = left;
parent->right = right;
insertHeap(heap, parent);
}
int arr[100], top = 0;
printCodes(extractMin(heap), arr, top);
}
int main() {
char data[] = {'a', 'b', 'c', 'd', 'e', 'f'};
int freq[] = {5, 9, 12, 13, 16, 45};
int size = sizeof(data) / sizeof(data[0]);
huffmanCodes(data, freq, size);
return 0;
}
```
这个函数接受三个参数:一个字符数组 `data`,一个整数数组 `freq`,以及一个整数 `size`。`data` 数组存储了要编码的字符,`freq` 数组存储了每个字符出现的频率,`size` 是数组的大小。函数首先构建哈夫曼树,然后按前序遍历输出每个字符的编码。在这个函数中,我们使用了一个小根堆来构建哈夫曼树。
阅读全文