You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
constchar SPECIAL_CH = '$';
const string FIRST_ALPHA = "0";
const string SECOND_ALPHA = "1";
structHffTreeNode {
// One of the input characterschar ch;
// Frequency of the characteruint32_t freq;
// Left and right child
HffTreeNode *left, *right;
HffTreeNode(char ch, uint32_t freq) {
left = right = NULL;
this->ch = ch;
this->freq = freq;
}
};
structCode {
char ch;
string bin;
};
// For comparison of// two heap nodes (needed in min heap)structCompare {
booloperator()(HffTreeNode* l, HffTreeNode* r) {
return l->freq > r->freq;
}
};
// Prints huffman codes from// the root of Huffman Tree.voidbuildCodes(vector<Code> &codes, structHffTreeNode* root, string str) {
if (!root) return;
if (root->ch != SPECIAL_CH) codes.push_back(Code{root->ch, str});
buildCodes(codes, root->left, str + FIRST_ALPHA);
buildCodes(codes, root->right, str + SECOND_ALPHA);
}
// The main function that builds a Huffman Tree and// print codes by traversing the built Huffman Tree
HffTreeNode* HuffmanCodes(vector<char> alpha, vector<int> freq) {
int size = (int) alpha.size();
structHffTreeNode *left, *right, *top;
// Create a min heap & inserts all characters of alpha[]
priority_queue<HffTreeNode*, vector<HffTreeNode*>, Compare> minHeap;
for (int i = 0; i < size; ++i) {
minHeap.push(newHffTreeNode(alpha[i], freq[i]));
}
#definepop_heap(heap) heap.top(); heap.pop();
// Iterate while size of heap doesn't become 1while (minHeap.size() != 1) {
// Extract the two minimum// freq items from min heap
left = pop_heap(minHeap);
right = pop_heap(minHeap);
// Create a new internal node with frequency equal to the sum of the// two nodes frequencies. Make the two extracted node as left and right// children of this new node. Add this node to the min heap '$'// is a special value for internal nodes, not used
top = newHffTreeNode(SPECIAL_CH, left->freq + right->freq);
top->left = left;
top->right = right;
minHeap.push(top);
}
return minHeap.top();
}
// Usage:// vector<char> alpha = { 'a', 'b', 'c', 'd', 'e', 'f' };// vector<int> freq = { 5, 9, 12, 13, 16, 45 };// HffTreeNode* root = HuffmanCodes(alpha, freq);// vector<Code> codes;// buildCodes(codes, root, "");// for(auto &code: codes) cout << code.ch << ": " << code.bin << endl;
The text was updated successfully, but these errors were encountered:
The text was updated successfully, but these errors were encountered: