Sergey Kim
Sergey Kim

Reputation: 397

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;
}

Upvotes: 0

Views: 1205

Answers (2)

rflobao
rflobao

Reputation: 597

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);
    }
};

Upvotes: 1

9T9
9T9

Reputation: 698

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;

Upvotes: 0

Related Questions