看来我为霍夫曼编码程序创建二叉树的代码有缺陷。我不知道为什么,但是当我在调试器中检查根节点时,左节点指向字母 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 函数有效。