From 32a48a7f2aebc2296a68752c3d50c60436ac1a8c Mon Sep 17 00:00:00 2001 From: Yevhen Kozirovskyi Date: Sun, 19 Jan 2025 17:17:10 +0000 Subject: [PATCH] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20sk1/compressor.c?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sk1/compressor.c | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/sk1/compressor.c b/sk1/compressor.c index 3429d0d..10db640 100644 --- a/sk1/compressor.c +++ b/sk1/compressor.c @@ -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 @@ -134,7 +153,7 @@ void storeCodes(struct MinHeapNode* root, char** codes, char* currentCode, int t if (!(root->left) && !(root->right)) { currentCode[top] = '\0'; if (root->data < 256) { // Ensure data is within bounds - codes[root->data] = strdup(currentCode); + codes[root->data] = strdup(currentCode); } } }