简体   繁体   English

我的二叉搜索树插入逻辑有什么问题?

[英]What is wrong with my binary search tree insertion logic?

binarysearch.h :二进制搜索.h:

#ifndef BST_BINARYSEARCH_H
    #define BST_BINARYSEARCH_H

    struct Node{
        int value;
        Node* left;
        Node* right;
    };

    class BST{
    public:
        Node* root;
        BST(){
            root = nullptr;
        }
        Node* insertNode(Node* root, Node toInsert);
        void inOrder(Node* root);
    };

    #endif //BST_BINARYSEARCH_H

binarysearch.cpp :二进制搜索.cpp:

#include 
    #include 
    #include "binarysearch.h"

    Node* BST::insertNode(Node* root, Node toInsert) {
        if(root == nullptr){
            root = &toInsert;
        }
        else {
            if (toInsert.value value)
                root->left = insertNode(root->left, toInsert);
            else
                root->right = insertNode(root->right, toInsert);
        }
        return root;
    }

    void BST::inOrder(Node *root) {
        if(root!= NULL){
            inOrder(root->left);
            std::coutvalue;
            inOrder(root->right);
        }
    }

main.cpp:主.cpp:

#include 
    #include "binarysearch.h"

    int main() {

        BST bst;
        Node* root = nullptr;

        Node a;
        a.value = 4;
        a.left = NULL;
        a.right = NULL;

        root = bst.insertNode(root, a);
        bst.insertNode(root, a);
        a.value = 5;
        bst.insertNode(root, a);
        a.value = 6;
        bst.insertNode(root, a);
        a.value = 7;
        bst.insertNode(root, a);
        a.value = 8;
        bst.insertNode(root, a);

        bst.inOrder(root);
        return 0;
    }

Apparently my root keeps moving from the original position as I insert more items.显然,当我插入更多项目时,我的根不断从原始位置移动。

I am getting Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) on bst.inOrder(root).我正在 bst.inOrder(root) 上以退出代码 139(被信号 11:SIGSEGV 中断)完成 Process。

What is the issue here?这里有什么问题?

The issue is with the insert node function, here you say if the tree is empty, we set the root to be the address of "toInsert".问题在于插入节点功能,这里你说如果树是空的,我们将根设置为“toInsert”的地址。 The problem here is toInsert isn't a reference, it's passed by copy.这里的问题是 toInsert 不是引用,它是通过副本传递的。 Which means toInsert is a temporary local copy variable, which expires as soon as the function ends.这意味着 toInsert 是一个临时的本地副本变量,一旦函数结束它就会过期。 Meaning your root pointer now doesn't point to anything.这意味着您的根指针现在不指向任何内容。

   //NOTE: Passing toInsert, copy is made
   Node* BST::insertNode(Node* root, Node toInsert) {
        //NOTE: root is null, so we set it to point to the node's copy
        if(root == nullptr){
            root = &toInsert;
        }
      //NOTE: The copy is destroyed because we ran out of scope
    }

Solution would be to make "toInsert" a pointer, or a reference解决方案是使“toInsert”成为指针或引用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM