这是我的遍历方法:
Result:
Running test tool.
$
command: "help"
Result:
|'exec <testname>' or 'exec !<testnum>'
|0 BQ1
|1 BS1
|2 BA1
|3 BP1'
$
command: "exec !2"
Result:
|||TEST BA1_ACTIVE
$
command: "exec !0"
Result:
|||TEST BQ1_ACTIVE
$
command: "help"
Result:
|'exec <testname>' or 'exec !<testnum>'
|0 BQ1
|1 BS1
|2 BA1
|3 BP1'
$
command: "exec !1"
Result:
|||TEST BS1_ACTIVE
$
command: "exec !3"
Result:
|||TEST BP3_ACTIVE
$
command: "quit"
Result:
Quitting.
这是我所拥有的输出:
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;
}
它似乎工作正常但我拥有所有这些我不应该拥有的垃圾值,我无法查明问题。
我怀疑控制结构有问题,我的逻辑是正确的,还是我应该使用if语句?
答案 0 :(得分:0)
我通过将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];
}
}
答案 1 :(得分:0)
即使使用&#34;修复&#34;你在答案中发布了,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;
}