BST pointer problem root pointer

Hi everyone

I'm new to c++ programming, I have a problem in the following Binary search tree code .

when I initialize (root = NULL) , the code compiles ,but when I run it stopped working.
if I remove the initialization it works , but I can't proceed with the binary tree as I can't initialize any pointer to NULL.

please HELP ..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  #include <iostream>

    using namespace std;

    struct node
    {
    int key;
    node *left;
    node *right;
    };

    void insert_new(node *&root, int key)
    {

        root->key = key;
        root->left = NULL;
        root->right = NULL;

    }


    int main()
    {
    node *root = new node;
    root = NULL;
    
    insert_new(root,50);
    return 0;
    }


line 20
*&root is equal to root
no difference ...
I know They're equal . The question is "why the program crashes when I set root to NULL ?"
If you know they're equal, then you should know that you cant access values of a null variable because they don't have any.

1
2
3
4

        root->key = key;
        root->left = NULL;
        root->right = NULL;


All of this is invalid because root is null. You need to stop where you are and re-review pointers, continuing will only make this more complicated.
Last edited on
yeah , I forget to use temp pointer ...

It finally worked , thank you all

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

#include <iostream>

using namespace std;

struct node
{
    int key;
    node *left;
    node *right;
};

void create_first_node(node *&root,int key)
{
    node *temp = new node;
    temp->key = key;
    temp->left = NULL;
    temp->right = NULL;
    root = temp;
}

void insert_new(node *&root, int key)
{

    if (root != NULL)
    {
      if(key > root->key)
      {
          insert_new(root->right,key);
      }
      else
    {
        if(key < root->key)
      {
          insert_new(root->left,key);
      }
    }
    }
    else
    {
        node *temp = new node;
        temp->key = key;

        root = temp;
        temp->left = NULL;
        temp->right = NULL;
}
}


int main()
{
    node *root = new node;
    root->right = NULL;
    root->left = NULL;

    create_first_node(root,50);
    insert_new(root,100);
    insert_new(root,20);
    insert_new(root,70);

     cout << root->key ;


    return 0;
}

Topic archived. No new replies allowed.