好的,我尝试自己制作 Hauffman 代码,但当我尝试使用递归方法为每个字母打印相应的代码时遇到问题。
(此时我已经创建了一个 BinaryTree 并且 root 不是 NULL)每个节点都有一个值,如果它是一个叶子,它也有一个字母,所以我开始一个节点一个节点地向下遍历树,但似乎在递归方法中node只是忘记了他是谁或者我不知道,我尝试了很多东西。:S
递归方法是createCode (Node* actual, string actualCode);
这是代码:
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string>
#include <queue>
using namespace std;
#define MAX_VALUE 256
int frequencies[MAX_VALUE] = {0};
struct Node {
int value;
char letter;
struct Node *Left, *Right;
}*root=NULL, *temp, *left_temp, *right_temp;
struct CompareNode : public std::binary_function<Node*, Node*, bool> {
bool operator()(const Node* lhs, const Node* rhs) const {
if (lhs->value == rhs->value)
return lhs->letter > rhs->letter;
else
return lhs->value > rhs->value;
}
};
void createCode(Node* actual,string actualCode) {
if (actual->Left == NULL && actual->Right == NULL) {
cout << "For: " << actual->letter << " is " << actualCode << endl;
}
else {
if (actual->Left) {
createCode(actual->Left, actualCode + "0");
}
if (actual->Right) {
createCode(actual->Right, actualCode + "1");
}
}
}
void createTree() {
priority_queue<Node*, vector<Node*>, CompareNode> que;
for (int x = 0; x < MAX_VALUE; x++) {
if (frequencies[x] > 0) {
temp = new Node;
temp->value = frequencies[x];
temp->letter = char(x);
que.push(temp);
}
}
while (que.size() > 1) {
temp = new Node();
temp->Left = que.top();
que.pop();
temp->Right = que.top();
que.pop();
temp->value = temp->Left->value + temp->Right->value;
temp->letter = NULL;
que.push(temp);
}
root = que.top();
que.pop();
}
void fillArray(int argc, char *argv[]) {
string line;
const char* ptr;
ifstream myFile(argv[argc - 1]);
if (myFile.is_open()) {
while (myFile.good()) {
getline(myFile,line);
if (line.length() != 0) {
ptr = &line.at(0);
while (*ptr != '\0')
++frequencies[*ptr++];
}
}
}
else
cout << "The file could not be open.";
}
int main(int argc, char *argv[]) {
fillArray(argc, argv);
createTree();
createCode(root, "");
return 0;
}
这是示例树(我试图发布图像,但因为我是新手,所以我不能):
这是输出:
For: a is 0
For: is 10
Segmentation fault: 11
请帮忙 :(