-1

这是我的遍历方法:

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 语句?

4

2 回答 2

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];
    }
}
于 2018-05-04T15:18:57.373 回答
0

即使您在答案中发布了“修复”,您也会遇到同样的问题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;
        }
于 2018-05-04T15:40:41.000 回答