3

わかりました、ハウフマン コードを自分で作成しようとしましたが、再帰的な方法で各文字に対応するコードを出力しようとすると問題が発生します。

(この時点で、私は既に BinaryTree を作成しており、ルートは NULL ではありません) 各ノードには値があり、それがリーフの場合は文字も含まれているため、ノードごとにツリーを下っていきますが、再帰的な方法ではノードは彼が誰であるかを忘れただけか、わかりません。私は多くのことを試しました。: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

助けてください :(

4

1 に答える 1

1

キューにプッシュするsを作成するときに、LeftRightポインタを初期化する必要があります。NULLNode

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無効なポインターを間接参照していることになります。

于 2012-11-15T02:30:31.537 に答える