tags:

views:

140

answers:

1

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);

        }
    }
}
+2  A: 

First I would recommend not mixing instances and pointers, your task will be much simpler if you choose one. In this case I think it would be appropriate to store a pointer to a Node in the heap, rather than an instance, the added benefit is that pointers behave more like you are accustomed to from Java, no need to worry about copy construction and assignment. You only need to remember to delete them (unlike in Java), something that can be done in the dtor of Heap.

Secondly, to answer the question in your code comment: No the copy ctor is not invoked in Heap::insert(), rather the assignment operator is invoked. Whether that is a problem or not depends on what your Node class looks like.

Andreas Magnusson