以下代码段未返回正确的文本。该代码采用指向霍夫曼代码树根节点的指针和二进制文本,然后将其转换。但是,每次返回一个重复的字母。
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的数字。