Skip to content
Advertisement

Recursion under a heap class

I am trying to solve the following problem.

“Define a recursive method named inOrderTraverse under the Heap class to perform inorder traversal over the nodes in the heap.”

In the above problem, Do I convert the heap array to BST to run In order Traversal or Can I perform In order traversal over a heap array using recursion? if so How? Any other different insights on the problem will also be helpful.

If you want to check the whole code, https://github.com/iaminhri/DSATheoriesAndCodes/blob/main/src/Heap.java

I am only facing on the following section where I have to traverse a heap using In Order Traversal using recursion.

public class Heap extends HeapSkeleton<Integer>{
    
public boolean isLeaf(int pos){
    return pos > currentSize/2;
}

public void inOrderTraversal(int pos){
    if(isLeaf(pos))
        return;
    else{
        inOrderTraversal(2 * pos);
        System.out.print(heapArr[2*pos] + " " );
        inOrderTraversal(2 * pos + 1);
    }
}
}

//Main Class

public class DSAClassDriverList {
    public DSAClassDriverList(){
        Heap newHeap = new Heap(10);
        newHeap.insert(5);
        newHeap.insert(10);
        newHeap.insert(20);
        newHeap.insert(3);
        newHeap.insert(13);
        newHeap.insert(7);

        newHeap.printHeap();

        System.out.print("In Order Sort: ");
        newHeap.inOrderTraversal(1);
    }

    public static void main(String[] args) { new DSAClassDriverList(); }
}

//The following output of the program which is not correct in terms of In order traversal.

enter image description here

Advertisement

Answer

The problem is that your function is printing heapArr[2*pos], which evidently means it can only ever print data at even indices.

Instead the function should have as goal to print the value of the given pos and of its subtrees.

This also means you need to change the stop condition: it should just verify that pos is a valid index (in range).

So:

public void inOrderTraversal(int pos){
    if (pos > currentSize) {
        return;
    } else {
        inOrderTraversal(2 * pos);
        System.out.print(heapArr[pos] + " " );
        inOrderTraversal(2 * pos + 1);
    }
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement