Binary search Tree adding this->root gives segment fault

Hello I am getting an error when I add this->root in all my functions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
bst::hwareItem* bst:: findNode(hwareItem*& root, char barcode[]){

    if(this->root==NULL)
        return NULL;
    else if (strcmp(this->root->barcode, barcode)==0)
        return this->root;
    else if(strcmp(this->root->barcode, barcode)<0){

        findNode(root->left, barcode);}
    else{

            findNode(root->right, barcode);}

}


says segmentation fault..but without adding this-> i dont get error..why?
Last edited on
This is because this->root is zero and parameter root is not zero.
Rewrite
 
bst::hwareItem* bst:: findNode(hwareItem*& root, char barcode[]){

as
 
bst::hwareItem* bst:: findNode(hwareItem*& root2, char barcode[]){

and check your logic, where you should write "this->root" as simple "root" and where you should write "root2".
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
int bst ::updateItem(hwareItem*& root, char bar[]){

    char newBar[10];

    if(root==NULL){
        cout<<"Item does not exist"<<endl;
        return 0;
        }
    else if (strcmp(root->barcode, bar)==0){
        cout<<"Enter new Barcode: ";

        cin.getline(newBar, 10);
        strcpy(root->barcode, newBar);
        cout<<root->barcode<<endl;//////////////////Here it shows right answer
                                                /but doesnot update item when function exit            
        return 0;

    }
    else if(strcmp(root->barcode, bar)<0){

        updateItem(root->left, bar);}
    else{

            updateItem(root->right, bar);}

}
May be you should write line 13 as strcpy(this->root->barcode, newBar);
I did but the first value deletes..new value is added also

1
2
3
4
5
6
7
8
9
10
in Main()
strcpy(item.bar, "5505505");//adds
    val.addNode(item);
    strcpy(item.bar, "1010101");//adds
    val.addNode(item);
    //cout<<val.findNode("1010101")<<endl;//outputs 1
    val.updateItem("1010101");//I add 99999
    cout<<val.findNode("5505505")<<endl;//this value is deleted
    cout<<val.findNode("99999")<<endl;//this value is found
Last edited on
Thanks guys I solved it...

The logic was messing up because I was replacing the key node value to separate right node from left...Actually I am not supposed to update key node value but other values which do not separate left and right subtrees based on lesser and greater equality

Struct node{

keyvalue; //this is needed to position nodes in the respective tree..
//other values;//these values could be changed but not keyvalue

}
Last edited on
Registered users can post here. Sign in or register to post.