不正确的二叉树
while(count != 25) {
tail = head;
new_node = (binary_node*)malloc(sizeof(binary_node));
while(tail->next != NULL)
tail = tail->next;
tail->next = new_node;
new_node->element.frequency = (p->element.frequency + q->element.frequency);
new_node->LSON = p;
new_node->LSON->RTAG = 0;
new_node->RSON = q;
new_node->RSON->RTAG = 1;
head = new_node;
n = n - 1;
head = q->next;
sort(n, head);
p = head;
q = p->next;
count++;
}
上面的代码应该生成一个哈夫曼树。然而,形成的二叉树是不正确的。所有包含字母的节点都应该是叶子或没有儿子的节点,但某些字母节点仍然有儿子。代码有什么问题吗?
while(count != 25) {
tail = head;
new_node = (binary_node*)malloc(sizeof(binary_node));
while(tail->next != NULL)
tail = tail->next;
tail->next = new_node;
new_node->element.frequency = (p->element.frequency + q->element.frequency);
new_node->LSON = p;
new_node->LSON->RTAG = 0;
new_node->RSON = q;
new_node->RSON->RTAG = 1;
head = new_node;
n = n - 1;
head = q->next;
sort(n, head);
p = head;
q = p->next;
count++;
}
The code above should generate a huffman tree. However, the binary tree that is formed is incorrect. All the nodes that contains a letter should be a leaf or a node without a son but some alphabet nodes still have sons. What is wrong with the code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
malloc
返回一个充满垃圾的内存区域。由于您从未将 new_node 设置为它不是字母表节点,有时您会发现那里有垃圾说它实际上是一个字母表节点。
验证结果:您应该找到更多原来拥有的字母节点。
malloc
returns you a memory area full of garbage.Since you never set for the new_node that it's not an alphabet node sometimes you'll find garabage there saying that it is actually an alphabet node.
consequence for verification: you should find more alphabet nodes that you originally had.