我正在尝试实现最小堆的就地算法。我将 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;
}
}
调试后,我得到了正确的输出,但是在以无序方式遍历它时,我得到了堆栈溢出异常。