'Why My output is printing # in Huffman coding
So I was implementing Huffman coding problem in which i wrote the below code and below is the output attached. Can any one tell me why I am getting # in the output:-
#include<bits/stdc++.h>
using namespace std;
class HuffTree
{
public:
int val;
char letter;
HuffTree* left, * right;
HuffTree(int val, char letter)
{
this->val = val;
this->letter = letter;
this->left = nullptr;
this->right = nullptr;
}
};
vector<pair<int, char>> FrequencyCount(string s)
{
map<char, int> mp;
for (int i = 0;i < s.size();i++)
mp[s[i]]++;
vector<pair<int, char>> v;
for (auto it : mp)
v.push_back(make_pair(it.second, it.first));
return v;
}
class Compare
{
public:
bool operator() (HuffTree* a, HuffTree* b)
{
return (a->val > b->val);
}
};
vector<pair<char, string >> huffmannCodes;
void printCodes(HuffTree* root, string str)
{
if (!root)
return;
if (root->val != '#')
huffmannCodes.push_back(make_pair(root->letter, str));
printCodes(root->left, str + "0");
printCodes(root->right, str + "1");
}
void makeTree(vector<pair<int, char>>& frq)
{
priority_queue<HuffTree*, vector<HuffTree*>, Compare> pq;
for (auto it : frq)
pq.push(new HuffTree(it.first, it.second));
while (pq.size() > 1)
{
HuffTree* left = pq.top();
pq.pop();
HuffTree* right = pq.top();
pq.pop();
HuffTree* newNode = new HuffTree(left->val + right->val, '#');
newNode->left = left;
newNode->right = right;
pq.push(newNode);
}
printCodes(pq.top(), "");
}
int main()
{
string s;
cin >> s;
vector<pair<int, char>> freqcount = FrequencyCount(s);
sort(freqcount.begin(), freqcount.end());
makeTree(freqcount);
for (auto it : huffmannCodes)
cout << it.first << "-->" << it.second << endl;
}
When I run the program this is what i am getting in the output:-
output
Can Anyone tell me why my output contains # as the node.
Any help will be appreciated.
Solution 1:[1]
if (root->val != '#') should be if (root->letter != '#').
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mark Adler |
