从堆的ArrayList实现中裁剪每个叶,可以通过以下步骤实现:
以下是一个示例代码片段,展示了如何从堆的ArrayList实现中裁剪每个叶节点(以最小堆为例):
import java.util.ArrayList;
public class MinHeap {
private ArrayList<Integer> heap;
public MinHeap() {
heap = new ArrayList<>();
}
public void insert(int value) {
heap.add(value);
heapifyUp(heap.size() - 1);
}
public int extractMin() {
if (heap.isEmpty()) {
throw new IllegalStateException("Heap is empty");
}
int minValue = heap.get(0);
int lastIndex = heap.size() - 1;
heap.set(0, heap.get(lastIndex));
heap.remove(lastIndex);
heapifyDown(0);
return minValue;
}
private void heapifyUp(int index) {
int parentIndex = (index - 1) / 2;
while (index > 0 && heap.get(index) < heap.get(parentIndex)) {
swap(index, parentIndex);
index = parentIndex;
parentIndex = (index - 1) / 2;
}
}
private void heapifyDown(int index) {
int leftChildIndex = 2 * index + 1;
int rightChildIndex = 2 * index + 2;
int smallestIndex = index;
if (leftChildIndex < heap.size() && heap.get(leftChildIndex) < heap.get(smallestIndex)) {
smallestIndex = leftChildIndex;
}
if (rightChildIndex < heap.size() && heap.get(rightChildIndex) < heap.get(smallestIndex)) {
smallestIndex = rightChildIndex;
}
if (smallestIndex != index) {
swap(index, smallestIndex);
heapifyDown(smallestIndex);
}
}
private void swap(int index1, int index2) {
int temp = heap.get(index1);
heap.set(index1, heap.get(index2));
heap.set(index2, temp);
}
public static void main(String[] args) {
MinHeap minHeap = new MinHeap();
minHeap.insert(5);
minHeap.insert(3);
minHeap.insert(8);
minHeap.insert(1);
while (!minHeap.isEmpty()) {
System.out.println(minHeap.extractMin());
}
}
}
在这个示例代码中,我们使用ArrayList来实现最小堆。insert方法用于插入元素,extractMin方法用于提取最小值。heapifyUp和heapifyDown方法用于调整堆的结构。通过调用insert方法插入元素,然后循环调用extractMin方法,我们可以按升序提取堆中的所有元素。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云