Обновить sk1/compressor.c
This commit is contained in:
parent
4125b24356
commit
32a48a7f2a
@ -104,6 +104,16 @@ struct MinHeap* createAndBuildMinHeap(unsigned char data[], int freq[], int size
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Build Huffman Tree
|
// Build Huffman Tree
|
||||||
|
void freeHuffmanTree(struct MinHeapNode* root) {
|
||||||
|
if (root == NULL) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
freeHuffmanTree(root->left);
|
||||||
|
freeHuffmanTree(root->right);
|
||||||
|
free(root);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build Huffman Tree with memory management
|
||||||
struct MinHeapNode* buildHuffmanTree(unsigned char data[], int freq[], int size) {
|
struct MinHeapNode* buildHuffmanTree(unsigned char data[], int freq[], int size) {
|
||||||
struct MinHeapNode *left, *right, *top;
|
struct MinHeapNode *left, *right, *top;
|
||||||
struct MinHeap* minHeap = createAndBuildMinHeap(data, freq, size);
|
struct MinHeap* minHeap = createAndBuildMinHeap(data, freq, size);
|
||||||
@ -112,13 +122,22 @@ struct MinHeapNode* buildHuffmanTree(unsigned char data[], int freq[], int size)
|
|||||||
left = extractMin(minHeap);
|
left = extractMin(minHeap);
|
||||||
right = extractMin(minHeap);
|
right = extractMin(minHeap);
|
||||||
|
|
||||||
|
// Create a new internal node with frequency equal to the sum of the two nodes
|
||||||
top = createNode('$', left->freq + right->freq);
|
top = createNode('$', left->freq + right->freq);
|
||||||
top->left = left;
|
top->left = left;
|
||||||
top->right = right;
|
top->right = right;
|
||||||
|
|
||||||
insertMinHeap(minHeap, top);
|
insertMinHeap(minHeap, top);
|
||||||
}
|
}
|
||||||
return extractMin(minHeap);
|
|
||||||
|
// Extract the final node, which is the root of the Huffman tree
|
||||||
|
struct MinHeapNode* root = extractMin(minHeap);
|
||||||
|
|
||||||
|
// Free the MinHeap structure
|
||||||
|
free(minHeap->array);
|
||||||
|
free(minHeap);
|
||||||
|
|
||||||
|
return root;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Print Huffman Codes to a map
|
// Print Huffman Codes to a map
|
||||||
@ -134,7 +153,7 @@ void storeCodes(struct MinHeapNode* root, char** codes, char* currentCode, int t
|
|||||||
if (!(root->left) && !(root->right)) {
|
if (!(root->left) && !(root->right)) {
|
||||||
currentCode[top] = '\0';
|
currentCode[top] = '\0';
|
||||||
if (root->data < 256) { // Ensure data is within bounds
|
if (root->data < 256) { // Ensure data is within bounds
|
||||||
codes[root->data] = strdup(currentCode);
|
codes[root->data] = strdup(currentCode);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user