Обновить sk1/compressor.c

This commit is contained in:
Yevhen Kozirovskyi 2025-01-19 17:17:10 +00:00
parent 4125b24356
commit 32a48a7f2a

View File

@ -104,6 +104,16 @@ struct MinHeap* createAndBuildMinHeap(unsigned char data[], int freq[], int size
}
// 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 *left, *right, *top;
struct MinHeap* minHeap = createAndBuildMinHeap(data, freq, size);
@ -112,13 +122,22 @@ struct MinHeapNode* buildHuffmanTree(unsigned char data[], int freq[], int size)
left = 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->left = left;
top->right = right;
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