I am creating a Huffman Tree and to do so I started with making a Min Heap. The heap is set up and works sorting the values by frequency in the document but my problem comes when I try to start creating the tree.
I am popping the top two items off the heap and putting a node above them and reinserting into the heap. The heap is array based so it does not touch the *left and *right pointers of the nodes. When the heap is down to only one node however both it's left and right node pointers are null so I believe it may be an issue with my pointers...? I am new to c++ from java for give my dumb mistakes.
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);
}
}
}