2

I am trying to implement in-place algorithm of min-heap. I converted the BST to sorted linked list, and following is the code snippet

public void inorder(Node root) {
    if (isEmpty(root))
        return;
    inorder(root.left);
    System.out.print(root.data + "  ");
    inorder(root.right);
}


    public void sortBST(Node root) {
    if (root == null)
        return;
    sortBST(root.right);
    if (head == null)
        head = root;
    else {
        root.right = head;
        head.left = root;
        head = head.left;
    }
    sortBST(root.left);
}

// Printing of sorted BST
public void printSortedBST(Node head) {
    Node temp = head;
    while (temp != null) {
        System.out.print(temp.data + "    ");
        temp = temp.right;
    }
    System.out.println("");
}

// In-place Minimum heap
public Node minHeap(Node head, Node root) {

    root = head;
    Queue<Node> queue = new ArrayDeque<Node>();
    queue.add(root);
    Node parent = null;
    while (head.right != null) {
        parent = queue.poll();
        head = head.right;
        queue.add(head);
        parent.left = head;

        if (head != null) {
            head = head.right;
            queue.add(head);
            parent.right = head;
        }
    }
    return root;
}

}

after debugging i am getting the proper output but while traversing it in inorder fashion i am getting stack overflow exception.

  • it is forming a infinite loop, if left and right of leaf node can be made to null then the problem can be solved. Thanks in advance – Shashank Agrawal Dec 21 '16 at 13:13

0 Answers0