Min heap 创建二叉搜索树最小堆的就地算法

Min heap 创建二叉搜索树最小堆的就地算法,min-heap,Min Heap,我正在尝试实现min-heap的就地算法。我将BST转换为排序链表,下面是代码片段 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

我正在尝试实现min-heap的就地算法。我将BST转换为排序链表,下面是代码片段

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;
}
public void索引(节点根){
if(isEmpty(root))
返回;
顺序(根。左);
System.out.print(root.data+“”);
顺序(root.right);
}
公共void sortBST(节点根){
if(root==null)
返回;
sortBST(root.right);
if(head==null)
头=根;
否则{
root.right=头部;
head.left=根;
head=head.left;
}
sortBST(根,左);
}
//分类BST的打印
公共数据库(节点头){
节点温度=头;
while(temp!=null){
系统输出打印(温度数据+“”);
温度=右侧温度;
}
System.out.println(“”);
}
//就地最小堆
公共节点minHeap(节点头、节点根){
根=头;
Queue Queue=new ArrayDeque();
添加(根);
节点父节点=null;
while(head.right!=null){
parent=queue.poll();
head=head.right;
队列。添加(头);
parent.left=头部;
if(head!=null){
head=head.right;
队列。添加(头);
parent.right=头部;
}
}
返回根;
}
}


调试后,我得到了正确的输出,但在以有序方式遍历它时,我得到了堆栈溢出异常。

它正在形成一个无限循环,如果可以将叶节点的左侧和右侧设置为null,那么问题就可以解决。提前谢谢