我正在尝试实现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;
}
}
调试后我得到了正确的输出但是在顺序遍历时我得到了堆栈溢出异常。