二叉搜索树C ++实现(动态内存问题)

时间:2015-03-31 21:11:02

标签: c++ binary-search-tree dynamic-memory-allocation

我目前正在学习如何实现二叉搜索树,但使用更基本的C方法(请不要#34;现在使用类")。但是,动态内存自身被删除存在很大问题。头值正确更新,但是,每个其他点都会被删除。谁能帮我?此外,如果您提供一些如何收紧树的实现的提示,那将是很好的。程序的基本纲要:输入一个字符,然后运行树的一个函数。但是请注意,这个实现是一个纯粹的BST,所以没有平衡。谢谢。

#include <iostream>

struct point{
    point* parent, *left, *right;

    int val = -1;
};

point* biggest;
point empty;

point search(int pos, bool near, point* loc = biggest){
    if(loc->val == pos){
        return *loc;
    } else if(loc->left->val != -1 and loc->val > pos){
        return search(pos, near, loc->left);
    } else if(loc->right->val != -1){
        return search(pos, near, loc->right);
    }

    if(near){
        return *loc;
    } else{
        point fail;
        return fail;
    }
}

void insert(int pos, point* res){
    point loc = search(pos, true);
    res->val = pos, res->left = &empty, res->right = &empty, res->parent = &loc;
    if(loc.val < res->val){
        loc.left = res;
    } else{
        loc.right = res;
    }

}

void remove(int pos){

}

int pred(int pos){
    point res = search(pos, false);
    if(res.val == -1){
        return -1;
    }

}

int succ(int pos){
    point res = search(pos, false);
    if(res.val == -1){
        return -1;
    }

}

void inorder(point* pos = biggest){
    if(pos->left->val != -1){
        inorder(pos->left);
    }
    std::cout << pos->val << " ";
    if(pos->right->val != -1){
        inorder(pos->right);
    }
}

int main() {
    point start;
    start.parent = &empty, start.left = &empty, start.right = &empty;
    biggest = &start;
    char c;
    int pos;
    do{
        std::cin >> c >> pos;

        switch (c){
            case 'S':
                std::cout << search(pos, false).val << std::endl;
                break;
            case 'I':
                if(biggest->val == -1){
                    start.val = pos;
                } else{
                    point* res = new point;
                    insert(pos, res);
                }
                break;
            case 'R':
                remove(pos);
                break;
            case 'P':
                std::cout << pred(pos) << std::endl;
                break;
            case 'N':
                std::cout << succ(pos) << std::endl;
                break;
            case 'O':
                inorder();
                std::cout << std::endl;
                break;
        }
    } while(c != '0');
    return 0;
}

1 个答案:

答案 0 :(得分:0)

除了代码中的许多怪异之外,我会在这里说:

void insert(int pos, point* res){
    point loc = search(pos, true);
    res->val = pos, res->left = &empty, res->right = &empty;
    res->parent = &loc; // <=== here

您修改res->parent以指向本地变量locinsert()函数返回后,point loc不再存在。

此外 已经在使用类;除了默认的成员可见性之外,C ++结构和类几乎完全相同。