Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/gwt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 需要帮助实现二进制搜索树吗_C++_Binary Search Tree - Fatal编程技术网

C++ 需要帮助实现二进制搜索树吗

C++ 需要帮助实现二进制搜索树吗,c++,binary-search-tree,C++,Binary Search Tree,我试图实现一个二进制搜索树,我遇到了这个人的代码,基本上是想复制它: 唯一的区别是,出于某种原因,此人没有将insert或search函数作为二进制搜索树类的成员函数。我基本上是想复制他的代码,但我希望这些操作成为类的一部分,因为这样做对我来说是有意义的……这不是应该做的方式吗 这就是我现在的代码: class BSTnode { public: BSTnode(int data) { BSTnode* right = nullptr; BSTnode* left = nul

我试图实现一个二进制搜索树,我遇到了这个人的代码,基本上是想复制它:

唯一的区别是,出于某种原因,此人没有将insert或search函数作为二进制搜索树类的成员函数。我基本上是想复制他的代码,但我希望这些操作成为类的一部分,因为这样做对我来说是有意义的……这不是应该做的方式吗

这就是我现在的代码:

class BSTnode {

public:
BSTnode(int data) {

    BSTnode* right = nullptr;
    BSTnode* left = nullptr;
    this->data = data;
}


int data;
BSTnode* right;
BSTnode* left;

};

class BinarySearchTree{
public:
BinarySearchTree() {

    root = nullptr;

}

BSTnode* insert(BSTnode* root, int data) {
    if (root == nullptr) {
        BSTnode* newNode = new BSTnode(data);
        root = newNode;
        return root;
    //  std::cout << root->data << endl;
    }

    if (data <= root->data) {

        root->left = insert(root->left, data);

    }
    else {

        root->right = insert(root->right, data);

    }

    return root;


}
public:
    BSTnode* root;

};
我主要有以下几点:

BinarySearchTree bst;
bst.insert(bst.root, 4);

bst.insert(bst.root, 3);
bst.insert(bst.root, 4);
bst.insert(bst.root, 3);
bst.insert(bst.root, 2);


std::cout << bst.root->data << std::endl;
我的第一个问题..我有一行代码

std::cout << bst.root->data << std::endl;
在我的主要演讲结束时,我只是想测试一下事情是否按预期进行。然而,当我试图运行这个程序时,程序崩溃了。调试该特定行时,会出现以下错误:

BST_INTERVIEW.exe中0x00e6160a处未处理的异常:0xC0000005:访问冲突读取位置0xCDCD

为什么会这样?其次 我的代码基本上就是让我插入的每个元素都成为新的根。当我调试时,它说每次插入时,条件root==nullptr为true,因此每个新元素基本上都被设置为根。我假设在第一次调用insert后,根没有指向BST的实际根节点,我假设这是因为我必须将此->根=新节点设置为仅根。但是我觉得我还需要在代码的其他地方添加这个,我只是有点困惑。有人能帮我把我的代码变成链接中的代码,但是BST是一个实际的对象,具有插入、搜索等成员函数吗


编辑:根据@Semyon Burov的回答,我将insert函数的参数更改为BSTnode*&。我还必须修复我的构造函数,它应该是this->left和this->right,而不是BSTnode*right和BSTnode*left

问题是,如果要更改函数中参数的值,应该将其作为引用或指针传递。然后你们把参数作为指针传递,你们不能改变指针的值,而是改变它所指向的值

BSTnode* insert(BSTnode* root, int data)

您可以按值将root传递给函数,因此它只在函数范围内更改。

您应该使用调试器检查程序。看起来您正在取消对未初始化或悬空指针的引用。我认为,如果函数的参数是指针,如插入函数中的BSTnode*,它将自动作为指针传递。将指针传递到包含BSTnode的内存,您可以更改该内存中的值,但无法更改指针