Search code examples
c++heaptraversalmin-heap

Getting garbage values when traversing min-heap


This is my traversal method:

void heapTraversal(){
        for(int i = 0; i<maxsize; i++){
            cout << "Current value is : " << hipa[i] << endl;
            if(hipa[(2*i)+1]){
                cout << "Left child is : " << hipa[(2*i)+1] << endl;
            }
            else{
                cout << "Left child does not exist" << endl;
            }
            if(hipa[(2*i)+2]){
                cout << "Right child is : " << hipa[(2*i)+2] << endl;
            }
            else{
                cout << "Right child does not exist" << endl;
            }

This is the output that I'm having:

Current value is : 7
Left child is : 9
Right child is : 17
Current value is : 9
Left child is : 15
Right child is : 12
Current value is : 17
Left child is : 25
Right child is : 22
Current value is : 15
Left child is : 1769234787
Right child does not exist
Current value is : 12
Left child does not exist
Right child does not exist
Current value is : 25
Left child does not exist
Right child is : 1852112910
Current value is : 22
Left child is : 1395618676
Right child is : 1701994856

It's seems to be working correctly yet I'm having all these garbage values which I shouldn't have, I couldn't pinpoint the issue.

I suspect there is something wrong with the control structures, is my logic correct or should I've used else if statements ?


Solution

  • Even with the "fix" you posted in your answer, you're going to run into the same problem whenever heap_size >= (maxsize/2). You have to check the computed left and right child indexes. Corrected code:

    void heapTraversal(){
        for(int i = 0; i<heap_size; i++){
            cout << "Current value is : " << hipa[i] << endl;
            int left = (2*i)+1;
    
            if(left < heap_size && hipa[left]){
                cout << "Left child is : " << hipa[left] << endl;
            }
            else{
                cout << "Left child does not exist" << endl;
            }
    
            int right = left+1;
            if(right < heap_size && hipa[right]){
                cout << "Right child is : " << hipa[right] << endl;
            }
            else{
                cout << "Right child does not exist" << endl;
            }