我正在创建一个哈夫曼树,为此我开始制作一个最小堆。该堆已经建立并能够按照文档中频率的排序方式进行排序,但当我尝试开始创建树时遇到了问题。
我弹出堆顶的两个项,并在它们上面放置一个节点,然后重新插入堆中。由于堆是基于数组的,所以它不会触及节点的左右指针。然而,当堆只剩下一个节点时,它的左右节点指针都为空,因此我认为这可能与我的指针有关……?我是从Java转到C++的新手,请原谅我的愚蠢错误。
我弹出堆顶的两个项,并在它们上面放置一个节点,然后重新插入堆中。由于堆是基于数组的,所以它不会触及节点的左右指针。然而,当堆只剩下一个节点时,它的左右节点指针都为空,因此我认为这可能与我的指针有关……?我是从Java转到C++的新手,请原谅我的愚蠢错误。
while(theHeap.getheapSize() > 1)
{
Node top;
Node *min1=new Node(theHeap.topandPop());
Node *min2=new Node(theHeap.topandPop());
top.left=min1;
top.right=min2;
top.freq=min1->freq+min2->freq;
theHeap.insert(top);
}
Node r=theHeap.topAndPop(); //null pointers for left and right children
--------------------------------------
//code for heap. arr is in the header file is Node *arr;
void Heap::insert(Node c)
{
if (heapSize != arrSize)
{
heapSize=heapSize+1;
arr[heapSize - 1] = c; //does this call copy constructor???
percolateUp(heapSize - 1);
}
}
void Heap::percolateUp(int nodeIndex) {
int parentIndex;
Node tmp;
if (nodeIndex != 0)
{
parentIndex = getParentPos(nodeIndex);
if (arr[parentIndex].freq > arr[nodeIndex].freq)
{
tmp = arr[parentIndex];
arr[parentIndex] = arr[nodeIndex];
arr[nodeIndex] = tmp;
percolateUp(parentIndex);
}
}
}
std::priority_queue
来实现堆吗? - James McNellistop
超出作用域,所以希望insert()
调用复制构造函数而不仅仅是取一个地址? - Reinderien