나는 허프만 트리를 만들고 있는데, 그렇게하기 위해서 나는 최소 힙을 만들기 시작했다. 힙이 설정되어 문서에서 빈도별로 값을 정렬하지만 나무를 만들기 시작할 때 문제가 발생합니다.C++ 허프 먼 트리 및 포인터
힙에서 상위 2 개 항목을 팝핑하고 그 위에 노드를 놓고 힙에 다시 삽입하고 있습니다. 힙은 배열 기반이므로 노드의 * 왼쪽 및 * 오른쪽 포인터를 건드리지 않습니다. 힙이 하나의 노드로 내려 갔을 때 둘 다 왼쪽 및 오른쪽 노드 포인터가 null이므로 포인터로 문제가 될 수 있다고 생각합니다 ...? 나는 자바에서 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'를 사용 해본 적이 있습니까? –
숙제가 주어지며 표준 라이브러리를 사용할 수 없습니다. – Westin
그냥'top'이 범위를 벗어나기 때문에'insert()'가 주소를 취하는 대신 복사 생성자를 호출하기를 바랍니다. – Reinderien