0
我試圖建立一個霍夫曼編碼樹。霍夫曼編碼樹
主:
int main()
{
// Read frequency table and build Huffman tree.
NodePtr huffman = build_tree();
print_tree(huffman);
// Free the allocated memory.
free_memory(huffman);
return 0;
}
輸入形式應爲上:
number of letters
"letter" number of occurrences
"letter2" number of occurrences
到目前爲止,我還沒有得到它的工作。任何想法可能是錯誤的?
build_tree功能:
NodePtr build_tree()
{
int characters;//number of characters
cin >> characters;
char letter;
int freq;
HuffmanPriorityQueue queue;
NodePtr p;
for (int i = 0 ; i < characters; i++)
{
cin >> letter;
cin >> freq;
NodePtr temp = new HuffmanNode(freq, letter);
queue.push(temp);
}
for (int i = 0 ; i < characters - 1 ; i++)
{
NodePtr a = queue.top();
queue.pop();
NodePtr b = queue.top();
NodePtr p = new HuffmanNode (a->frequency + b->frequency, NULL);
queue.push(p);
}
return p;
}
打印功能:哪個供給,所以我認爲它是正確的。
void print_tree(NodePtr root, int indent = 0, string prefix = "")
{
// External nodes are not printed.
if (root == NULL) {
return;
}
char letter = ' ';
if (root->is_leaf()) {
letter = root->letter;
}
cout << string(indent, ' ') << prefix << "(" << letter << " [" << root->frequency << "]";
if (root->is_leaf()) {
cout << ")" << endl;
} else {
cout << endl;
// Print left and right subtrees with the appropriate prefix, and
// increased indent (by INDENT_SIZE).
print_tree(root->left, indent + INDENT_SIZE, "0");
print_tree(root->right, indent + INDENT_SIZE, "1");
cout << string(indent, ' ') << ")" << endl;
}
}
看起來你不是太新StackOverlflow,但「到目前爲止,我還沒有得到它的工作」是不是開始一個問題的最佳場所。什麼不工作,你有沒有發現在調試任何麻煩,等 – crashmstr
是的,我是新來的StackOverflow和相對較新的C++所以請原諒我的無知:)。 錯誤是在build_tree功能,我無法弄清楚它的起源來自即使我已經試過了調試器(而不是在調試方面的專家或者不幸的是:() – user3265963
我認爲'NODEPTR P =新HuffmanNode( A->頻率+ B->頻率,NULL);'應該是這樣'NODEPTR p值=新HuffmanNode(A,b);' – Jarod42