1

i'm trying to implement my own binary search tree, i've stucked on inserting data, can you explain me what i'm doing wrong .

void tree::add(int data) {
    tree * tmp = new tree;

    if (root == NULL) {
        root = tmp;
        root->data = data;
        root->left = NULL;
        root->right = NULL;
    }
    else if (data <= root->data) {  
        left = tmp;
        left->data = data;
        left->left = NULL;
        left->right = NULL;

        while (tmp != NULL) {
            if (data <= left->data) {
                tmp = left->left;
            } else {
                tmp = left->right;
            }

        }
}

I'm trying to fill left node, if data i smaller than root but if data is greater than this leaf but still smaller than root it should be right child, but actually i have access volation

Rooster
  • 13
  • 3
  • And what does your debugger show you? It should take you to the line where the error happens, and let you inspect all the variables. – Useless Apr 09 '19 at 09:11
  • 1
    "can you explain me what i'm doing wrong" not working with pen and paper I'd say. Do some freaking drawings! – YSC Apr 09 '19 at 09:12

1 Answers1

0

You should revise the logic of your algorithm:

//here you set the pointers to null 
left->left = NULL;
left->right = NULL;

while (tmp != NULL) {
    if (data <= left->data) {
        // here at the first time 
        tmp = left->left;
    } else {
        // or here 
        tmp = left->right;
    }
    // tmp will be set to null and the exection will end immediately
}
NiVeR
  • 9,644
  • 4
  • 30
  • 35