我当前正在制作MaxHeap程序,我需要按级别顺序打印堆。如何才能做到这一点?我是否要创建一种方法以在堆类内部按级别顺序打印堆,还是在主类中进行打印?我知道像我的二叉搜索树项目一样,我使用迭代方法并从主类中调用它们,但是我不确定是否可以在这里进行。下面是我的课本中对MaxHeap类的实现:
public final class MaxHeap<T extends Comparable<? super T>> implements MaxHeapInterface<T>
{
private T[] heap;
private int lastIndex;
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 25;
private static final int MAX_CAPACITY = 10000;
int swaps=0;
public MaxHeap() {
this(DEFAULT_CAPACITY);
}
public MaxHeap(int initialCapacity) {
if (initialCapacity < DEFAULT_CAPACITY)
initialCapacity = DEFAULT_CAPACITY;
else
checkCapacity(initialCapacity);
@SuppressWarnings("unchecked")
T[] tempHeap = (T[]) new Comparable[initialCapacity + 1];
heap = tempHeap;
lastIndex = 0;
initialized = true;
}
public T getMax() {
checkInitialization();
T root = null;
if (!isEmpty())
root = heap[1];
return root;
}