Daa 02
Daa 02
Assignment No: 02
struct MinHeap {
// Current size of min heap unsigned size;
// A utility function allocate a new min heap node with given character and frequency of the character
struct MinHeapNode* newNode(char data, unsigned freq) { struct MinHeapNode* temp = (struct
MinHeapNode*)malloc(sizeof(struct MinHeapNode)); temp->left = temp->right = NULL; temp->data
= data; temp->freq = freq; return temp;
}
}
// A utility function to insert a new node to Min Heap void insertMinHeap(struct
MinHeap* minHeap, struct MinHeapNode* minHeapNode) { ++minHeap->size;
int i = minHeap->size - 1; while (i && minHeapNode->freq < minHeap-
>array[(i - 1) / 2]->freq) { minHeap-
>array[i] = minHeap->array[(i - 1) / 2];
i = (i - 1) / 2;
} minHeap->array[i] = minHeapNode;
}
// Creates a min heap of capacity equal to size and inserts all character of data[] in min heap. Initially size
of min heap is equal to capacity struct MinHeap* createAndBuildMinHeap(char data[], int freq[], int
size) { struct MinHeap* minHeap = createMinHeap(size);
}
for (int i = 0; i < size; ++i) minHeap->array[i] = newNode(data[i],
freq[i]); minHeap->size = size; buildMinHeap(minHeap); return
minHeap;
}
// Step 4: The remaining node is the root node and the tree is complete.
return extractMin(minHeap);
// Prints huffman codes from the root of Huffman Tree. It uses arr[] to store codes void printCodes(struct
MinHeapNode* root, int arr[], int top) {
}
arr[top] = 0; printCodes(root->left, arr,
top + 1);
}
// The main function that builds a Huffman Tree and print codes by traversing
// the built Huffman Tree void HuffmanCodes(char
data[], int freq[], int size) { //
Construct Huffman Tree
struct MinHeapNode* root = buildHuffmanTree(data, freq, size);