binary search tree with void

I can't manage to make this work with a void in line 20, i can with a return struct function, but with this as soon as i call data at line 39 the program crashes.

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
  #include <iostream>
using namespace std;

struct Bst{
    int data;
    Bst* high;
    Bst* low;
};

Bst* root=NULL;

Bst* getnew(int num){
    Bst* temp=new Bst;
    temp->data=num;
    temp->high=NULL;
    temp->low=NULL;
    return temp;
}

void add(Bst* p,int num){
    Bst* temp=getnew(num);
    if(p==NULL){
        p=temp;
        return;
    }
    if(num<=p->data){
        add(p->low,num);
    }
    else{
        add(p->high,num);
    }
}

int main(){
    add(root,20);
    add(root,15);
    add(root,10);
    add(root,5);
    cout << root->data << "\n";
}
Line 23 is only changing the local copy of the pointer address, and since you return right after that, it does nothing to your actual tree.
Last edited on
Topic archived. No new replies allowed.