简体   繁体   中英

binary search tree insert function c++

I have the following problem. I was coding in C++ 2 years ago and now decided to practice this language. I don't know what is going on, because compiler says it is an access viloation when I want to access root->data after insertion. May be I completely forgot programming concepts with memory allocation or etc, but help me please I can't see a mistake here! Thanks in advance!

#define BLACK 0

 #define RED 1

using namespace std;

struct Node {

    Node* left, *right;
    int data;
    bool color;

    Node(int key) {
        data = key;
        left = right = NULL;
        color = RED;
    }
};

struct RBTree {

    Node* root;

    RBTree() { root = NULL; }

    void insertBST(Node* node, int key) {

        if (node == NULL) {

            node = new Node(key);
        }

        else {

            if (key < node->data) {

                insertBST(node->left, key);
            }

            else {

                insertBST(node->right, key);
            }
        }
    }

    void insert(int key) {

        insertBST(root, key);
    }
};

int main()
{

    RBTree tree;
    tree.insert(10);

    cout << tree.root->data;
    _getch();
    return 0;
}

Try this:

struct RBTree {

    Node* root;

    RBTree() { root = NULL; }

    void insertBST(Node** node, int key) {

        if (*node == NULL) {

            *node = new Node(key);
        }

        else {

            if (key < (*node)->data) {

                insertBST(&(*node)->left, key);
            }

            else {

                insertBST(&(*node)->right, key);
            }
        }
    }

    void insert(int key) {

        insertBST(&root, key);
    }
};
if (node == NULL) {

        node = new Node(key);
 }

In the above code segment you are creating a new node when the root == NULL. But you are not assigning the newly created node to the root. Need to pass by reference as follow.

  T obj;
  if ( !ptr ) 
    ptr = &obj;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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