Data structures 我是否正确地插入到max堆中?
我正在准备期末考试,不确定是否正确插入了值Data structures 我是否正确地插入到max堆中?,data-structures,tree,Data Structures,Tree,我正在准备期末考试,不确定是否正确插入了值6、7、57、54、96、3、9、4、2、8、32。最后我看到一棵树,看起来像: 96 / \ 57 9 / \ / \
6、7、57、54、96、3、9、4、2、8、32
。最后我看到一棵树,看起来像:
96
/ \
57 9
/ \ / \
6 54 3 7
/ \ / \
4 2 8 32
有谁能告诉我这是不是正确的,或者这不是我的错?谢谢 这是正确的。你为什么认为自己搞砸了?这是正确的。你为什么认为你把事情搞砸了?是的,你说得对,解决方案是正确的 只要在表示二进制堆的列表末尾添加新元素,就可以对该元素应用heapify Heapify应该将该元素与其父元素进行比较,如果该元素更大,它应该交换这些元素并继续运行,直到到达根元素为止 以下是一些阶段:
6 --> 7 --> 57
/ / \
6 6 7
下面是一个java示例:
public class BinaryMinHeap {
public void insert(int value) {
if (heapSize == data.length)
throw new HeapException("Heap's underlying storage is overflow");
else {
heapSize++;
data[heapSize - 1] = value;
heapify(heapSize - 1);
}
}
…
private void heapify(int nodeIndex) {
int parentIndex, tmp;
if (nodeIndex != 0) {
parentIndex = getParentIndex(nodeIndex);
if (data[parentIndex] < data[nodeIndex]) {
tmp = data[parentIndex];
data[parentIndex] = data[nodeIndex];
data[nodeIndex] = tmp;
heapify(parentIndex);
}
}
}
}
公共类二进制Minheap{
公共空白插入(int值){
if(heapSize==data.length)
抛出新的HeapException(“堆的底层存储溢出”);
否则{
heapSize++;
数据[heapSize-1]=值;
heapify(heapSize-1);
}
}
…
私有void heapify(int nodeIndex){
intparentindex,tmp;
如果(节点索引!=0){
parentIndex=getParentIndex(nodeIndex);
if(数据[parentIndex]<数据[nodeIndex]){
tmp=数据[父索引];
数据[父索引]=数据[节点索引];
数据[节点索引]=tmp;
heapify(父母指数);
}
}
}
}
代码来源:是的,您的解决方案是正确的 只要在表示二进制堆的列表末尾添加新元素,就可以对该元素应用heapify Heapify应该将该元素与其父元素进行比较,如果该元素更大,它应该交换这些元素并继续运行,直到到达根元素为止 以下是一些阶段:
6 --> 7 --> 57
/ / \
6 6 7
下面是一个java示例:
public class BinaryMinHeap {
public void insert(int value) {
if (heapSize == data.length)
throw new HeapException("Heap's underlying storage is overflow");
else {
heapSize++;
data[heapSize - 1] = value;
heapify(heapSize - 1);
}
}
…
private void heapify(int nodeIndex) {
int parentIndex, tmp;
if (nodeIndex != 0) {
parentIndex = getParentIndex(nodeIndex);
if (data[parentIndex] < data[nodeIndex]) {
tmp = data[parentIndex];
data[parentIndex] = data[nodeIndex];
data[nodeIndex] = tmp;
heapify(parentIndex);
}
}
}
}
公共类二进制Minheap{
公共空白插入(int值){
if(heapSize==data.length)
抛出新的HeapException(“堆的底层存储溢出”);
否则{
heapSize++;
数据[heapSize-1]=值;
heapify(heapSize-1);
}
}
…
私有void heapify(int nodeIndex){
intparentindex,tmp;
如果(节点索引!=0){
parentIndex=getParentIndex(nodeIndex);
if(数据[parentIndex]<数据[nodeIndex]){
tmp=数据[父索引];
数据[父索引]=数据[节点索引];
数据[节点索引]=tmp;
heapify(父母指数);
}
}
}
}
代码源:我总是对我所做的事情表示怀疑,并且喜欢让它再次检查以确保我了解算法的工作原理。我总是对我所做的事情表示怀疑,并且喜欢让它再次检查以确保我了解算法的工作原理。您总是在堆的末尾添加新元素,然后调用heapify(或此处
maxHeapify()
)您总是在堆的末尾添加新元素,然后调用heapify(或此处maxHeapify()
)