【发布时间】: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 个字符是否在codestd::string 是字符 '0' 也就是 ASCII 码 48。 -
我喜欢你的
Node课程。您会惊讶于有多少人不费心确保链接指针为空。 -
@Sam Varshavchik,抱歉应该是“0”。在我发布之前就发现了它,但没有编辑它。
-
@PaulMcKenzie,调试器输出“[Inferior 1 (process 20521) exited normal]”
标签: c++ tree huffman-code inorder postorder