C++ 使用哈夫曼树对二进制文本进行解码

C++ 使用哈夫曼树对二进制文本进行解码,c++,tree,huffman-code,inorder,postorder,C++,Tree,Huffman Code,Inorder,Postorder,下面的代码段未返回正确的文本。该代码接收一个指向哈夫曼代码树根节点的指针和一个二进制文本,然后进行转换。但是,每次它返回一个重复的字母 string decode(Node *root, string code) { string d = ""; char c; Node *node = root; for (int i = 0; i < code.size(); i++) { node = (code[i] == '0') ? node->left_

下面的代码段未返回正确的文本。该代码接收一个指向哈夫曼代码树根节点的指针和一个二进制文本,然后进行转换。但是,每次它返回一个重复的字母

string decode(Node *root, string code) {
    string d = ""; char c; Node *node = root;
    for (int i = 0; i < code.size(); i++) {
        node = (code[i] == '0') ? node->left_child : node->right_child;
        if ((c = node->value) < 128) {
            d += c;
            node = root;
        }
    }
    return d;
}
构建树的代码:

Node* buildTree(vector<int> in, vector<int> post, int in_left, int in_right, int *post_index) {
    Node *node = new Node(post[*post_index]);
    (*post_index)--;

    if (in_left == in_right) {
        return node;
    }

    int in_index;
    for (int i = in_left; i <= in_right; i++) {
        if (in[i] == node->value) {
            in_index = i;
            break;
        }
    }

    node->right_child = buildTree(in, post, in_index + 1, in_right, post_index);
    node->left_child = buildTree(in, post, in_left, in_index - 1, post_index);

    return node;
}
示例I/O: 输入:
101010111
输出:
A�A.�A.��A.�AAA


菱形字符大于128。< /P> < P>您将值放入 char ,这对于大多数C++编译器是签名的。但并非全部——字符是有符号的还是无符号的都是由实现定义的。有符号字符的范围为–128到127,因此它总是小于128。(您的编译器应该警告您这一点。)

您需要使用
intc而不是
字符c
decode()
中,并执行
d+=(char)c。然后,您的第一个代码段将正确返回阿拉巴马州


顺便说一下,需要在
decode()
中进行错误检查,以验证退出循环时
节点
是否等于
。否则,会有一些位在代码中间结束,因此不会被解码成符号。

您的调试器使用情况如何?您会惊讶地发现,“<代码>代码[i]=0</代码>”不重复,不检查
code
std::string中的第I个字符是否为字符“0”即ASCII代码48。我喜欢您的
节点
类。你会惊讶于有多少人懒得确保链接指针为空。@Sam Varshavchik,很抱歉应该是“0”。在我发布之前,它被抓到了,但没有编辑掉。@PaulMcKenzie,调试器输出“[Subsier 1(进程20521)正常退出]”树是正确的。如果再次运行顺序遍历和顺序遍历,则它们都匹配。此外,我还添加了错误检查。
Node* buildTree(vector<int> in, vector<int> post, int in_left, int in_right, int *post_index) {
    Node *node = new Node(post[*post_index]);
    (*post_index)--;

    if (in_left == in_right) {
        return node;
    }

    int in_index;
    for (int i = in_left; i <= in_right; i++) {
        if (in[i] == node->value) {
            in_index = i;
            break;
        }
    }

    node->right_child = buildTree(in, post, in_index + 1, in_right, post_index);
    node->left_child = buildTree(in, post, in_left, in_index - 1, post_index);

    return node;
}
        130
       /   \
     129    65
    /   \
  66     128
        /   \
      76     77