好的,我已经尝试用我自己的方法来制作Hauffman代码,当我试图用递归方法打印对应于每个字母的代码时,我遇到了一个问题。
(到目前为止,我已经创建了一个BinaryTree,根不是NULL)每个节点都有一个值,如果它是一个叶,它也有一个字母,所以我开始逐节点向下移动,但是在递归方法中,节点似乎只是忘记了他是谁,或者我不知道,我尝试了很多事情。:S
递归方法是createCode(Node*实数,字符串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请帮助:(
发布于 2012-11-15 02:30:31
创建进入队列的Left和Right指针时,需要初始化指向NULL的Node和Node指针:
if (frequencies[x] > 0) {
temp = new Node;
temp->Left = NULL;
temp->Right = NULL;
temp->value = frequencies[x];
temp->letter = char(x);
que.push(temp);
}如果没有显式初始化,这些指针具有不确定的值,而通常不是NULL,因此在createCode中,您正在取消引用无效指针。
https://stackoverflow.com/questions/13390374
复制相似问题