【发布时间】:2014-05-02 04:20:35
【问题描述】:
我的霍夫曼树有问题;当我尝试构建它时,我将节点放在错误的位置。例如,我希望我的权重为 2 的节点(带有子 i:1 和 n:1)进入 m:2 和 space:3 的节点之间,但它正好在我放入的前一个节点之后(2与 e:1 和 g:1 的孩子)。
我的问题是:如何根据权重(即两个子节点的总和)和子节点符号(即右孩子'n'在'g'的另一个右孩子之前)。
感谢您的帮助!
编辑:另外,我如何按字母顺序打印树的代码;现在我让他们从最右边的树打印到最左边
这是我的插入函数...
struct node* insert(struct node* head, struct node* temp)
{
struct node* previous = NULL;
struct node* current = head;
printf("entering insert function\n");
// finds the previous node, where we want to insert new node
while (temp->freq > current->freq && current->next != NULL)
{
printf("traversing: tempfreq is %lu and currentfreq is %lu\n", temp->freq, current->freq);
previous = current;
current = current->next;
}
if (current->next == NULL)
{
printf("hit end of list\n");
temp = current->next;
}
else
{
printf("inserting into list\n");
temp->next = current;
previous->next = temp;
}
return head;
}
【问题讨论】:
-
关于您的附加问题:在树中,字母顺序消失了。如果要按字母顺序创建代码表,请创建一个包含代码和编码字母的结构的无序数组,然后按字母对该表进行排序。或者,创建一个包含所有可能字母(但可能更多,最好是所有 ASCII 字符)的数组,并将其 Huffman 代码初始化为
""或 null。然后在遍历树时将霍夫曼代码写入相应的字段。然后扫描数组并打印它,跳过任何空条目。 -
我该怎么做呢?我想在我已经拥有的结构中添加一个数组吗?
-
您需要一个单独的数据结构以及 Huffman 树。例如,您可以将 char 缓冲区添加到包含 0 和 1 字符的代码的节点结构中。然后创建指向(现有)节点的指针的线性数组。
标签: c insert linked-list huffman-code