【问题标题】:Using a huffman tree to decode binary text使用霍夫曼树解码二进制文本
【发布时间】:2018-11-24 03:34:27
【问题描述】:

下面的 sn-p 没有返回正确的文本。该代码接收指向 Huffman 代码树根节点的指针和二进制文本,然后对其进行转换。但是,每次它返回一个重复的字母。

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对象的代码:

class Node {
public:
  Node(int i, Node *l = nullptr, Node *r = nullptr) {
      value = i;
      left_child = l;
      right_child = r;
  }
  int value;
  Node *left_child;
  Node *right_child;
};

构建树的代码:

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 

示例 I/O: 输入:101010010111 输出:A�A�A��A�AAA

菱形字符是大于 128 的数字。

【问题讨论】:

  • 您是否使用过任何调试器?
  • 你会惊讶地发现“code[i] == 0”确实不是,我再说一遍,不检查第 i 个字符是否在code std::string 是字符 '0' 也就是 ASCII 码 48。
  • 我喜欢你的Node 课程。您会惊讶于有多少人不费心确保链接指针为空。
  • @Sam Varshavchik,抱歉应该是“0”。在我发布之前就发现了它,但没有编辑它。
  • @PaulMcKenzie,调试器输出“[Inferior 1 (process 20521) exited normal]”

标签: c++ tree huffman-code inorder postorder


【解决方案1】:

您将值放在char 中,对于大多数 C++ 编译器来说,它是经过签名的。但并非全部 - char 是有符号还是无符号是实现定义的。有符号字符的范围在 –128 到 127 之间,因此它总是小于 128。(您的编译器应该警告过您。)

您需要在decode() 中使用int c; 而不是char c;,并使用d += (char)c;。然后你的第一个代码 sn-p 将正确返回ALABAMA

顺便说一句,decode() 中需要进行错误检查,验证您退出循环时 node 是否等于 root。否则,提供的某些位在代码中间结束,因此不会被解码为符号。

【讨论】:

  • 树是对的。如果您再次遍历它们,则中序遍历和后序遍历都匹配。另外,我添加了错误检查。
猜你喜欢
  • 2014-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多