似乎我为霍夫曼编码程序创建二叉树的代码存在缺陷。我无法弄清楚为什么,但是当我检查调试器中的根节点时,左节点指向字母N而右节点指向父节点。父节点的左节点指向字母N,而右节点指向父节点。父节点的左子节点是字母N,而...(您可以看到它的位置)。这是问题所在的代码:
huff_sort(nodes); // sort nodes by weight
//-------BUILDING TREE------
while(nodes->size() != 1){ //Sorts nodes by weight and then removes two of them and replaces them with one
int w= (**beg).weight + (**(beg+1)).weight;
Node* p = new Node;
p->set_node(w, '*', *nodes->begin(), *(nodes->begin()+1)); //making it the parent node of the two lowest nodes
nodes->erase(nodes->begin(), nodes->begin()+2);
unsigned int i = 0;
while(w > (*nodes)[i]->weight && i <= nodes->size()){ //finds where to insert the parent node based on weight
i++;
}
if(i > nodes->size()) //if it needs to be inserted at the end
nodes->push_back(p);
else
nodes->insert(nodes->begin()+i, p);
delete p;
}
从以前的调试中,我知道huff_sort函数有效。
答案 0 :(得分:1)
在循环结束时,执行delete p
会使指针无效并释放刚刚插入的节点。