遍历最小堆时获取垃圾值

Getting garbage values when traversing min-heap

本文关键字:获取 遍历      更新时间:2023-10-16

这是我的遍历方法:

void heapTraversal(){
for(int i = 0; i<maxsize; i++){
cout << "Current value is : " << hipa[i] << endl;
if(hipa[(2*i)+1]){
cout << "Left child is : " << hipa[(2*i)+1] << endl;
}
else{
cout << "Left child does not exist" << endl;
}
if(hipa[(2*i)+2]){
cout << "Right child is : " << hipa[(2*i)+2] << endl;
}
else{
cout << "Right child does not exist" << endl;
}

这是我的输出:

Current value is : 7
Left child is : 9
Right child is : 17
Current value is : 9
Left child is : 15
Right child is : 12
Current value is : 17
Left child is : 25
Right child is : 22
Current value is : 15
Left child is : 1769234787
Right child does not exist
Current value is : 12
Left child does not exist
Right child does not exist
Current value is : 25
Left child does not exist
Right child is : 1852112910
Current value is : 22
Left child is : 1395618676
Right child is : 1701994856

它似乎工作正常,但我拥有所有这些我不应该拥有的垃圾值,我无法确定问题所在。

我怀疑控制结构有问题,我的逻辑是否正确,还是我应该使用 else if 语句?

即使您在答案中发布了"修复程序",您也会在heap_size >= (maxsize/2)时遇到同样的问题。您必须检查计算的左右子索引。更正的代码:

void heapTraversal(){
for(int i = 0; i<heap_size; i++){
cout << "Current value is : " << hipa[i] << endl;
int left = (2*i)+1;
if(left < heap_size && hipa[left]){
cout << "Left child is : " << hipa[left] << endl;
}
else{
cout << "Left child does not exist" << endl;
}
int right = left+1;
if(right < heap_size && hipa[right]){
cout << "Right child is : " << hipa[right] << endl;
}
else{
cout << "Right child does not exist" << endl;
}

我已经通过将 for 循环参数从 maxsize 更改为 heap_size 来解决此问题。 maxsize 应该是堆的容量,而 heap_size 是堆的当前大小。我为好奇的人添加了类声明的其余部分。

class minHeap{
int *hipa;
int maxsize;
int heap_size;
public:
minHeap(int size);
void minHeapbuild(int );
int root(int i){
return (i-1)/2;
}
int left(int i){
return (2*i+1);
}
int right(int i){
return (2*i+2);
}
int extractRoot();
void decreaseKey(int i, int newKey);
void deleteKey(int key);
void addKey(int key);
int getRoot(){
return hipa[0];
}
}