这是我的代码:
using namespace std;
class HuffmanTree
{
public:
int frequency;
HuffmanTree(){}
HuffmanTree(int freq)
{
frequency = freq;
}
int compareTo(HuffmanTree tree)
{
return frequency - tree.frequency;
}
}
class HuffmanLeaf : public HuffmanTree
{
public:
char value;
HuffmanLeaf(int freq, char val)
{
HuffmanTree(freq);
value = val;
}
}
class HuffmanNode : public HuffmanTree
{
public:
HuffmanTree left, right;
HuffmanNode(HuffmanTree l, HuffmanTree r)
{
HuffmanTree(l.frequency + r.frequency);
left = l;
right = r;
}
}
class HuffmanCode
{
static HuffmanTree buildTree(int charFreqs[])
{
priority_queue<HuffmanTree> pq;
for(int i = 0; i < sizeof(charFreqs)/sizeof(char); i++)
{
if(charFreqs[i] > 0)
pq.push(HuffmanLeaf(charFreqs[i], (char)i));
}
while (pq.size() > 1)
{
// two trees with least frequency
HuffmanTree a = pq.top();
pq.pop();
HuffmanTree b = pq.top();
pq.pop();
// put into new node and re-insert into queue
pq.push(HuffmanNode(a, b));
}
HuffmanTree c = pq.top();
pq.pop();
return c;
}
}
static void printCodes(HuffmanTree tree, string prefix) {
//assert tree != null;
HuffmanTree* baseClass;
HuffmanLeaf* leafClass;
HuffmanNode* nodeClass;
if (typeid(*baseClass) == typeid(HuffmanLeaf))
{
HuffmanLeaf leaf = (HuffmanLeaf)tree;
// print out character, frequency, and code for this leaf (which is just the prefix)
cout<<leaf.value<<"\t"<<leaf.frequency<<"\t"<<prefix;
}
else if (typeid(*baseClass) == typeid(HuffmanNode))
{
HuffmanNode node = (HuffmanNode)tree;
// traverse left
prefix.append("0");
printCodes(node.left, prefix);
prefix.erase(prefix.length()-1);
// traverse right
prefix.append("1");
printCodes(node.right, prefix);
prefix.erase(prefix.length()-1);
}
}
我不知道如何解决线路失败的问题
HuffmanNode node = (HuffmanNode)tree;
HuffmanLeaf leaf = (HuffmanLeaf)tree;
我知道它与类型转换有关,并且我对 dynamic_cast、static_cast 和其他两个进行了研究,但我似乎无法弄清楚它的要求。任何帮助,将不胜感激。如果您发现任何其他问题,请告诉我。