简体   繁体   中英

why there's bug if i use static variable in recursive function ? c++

what am i trying to do is write binary search tree insertion function...i know there are other ways to write this program...but i am curious about this function why doesn't it work? my code is -

void insertionbst(struct node *root,int key){  
static struct node *n = newnode(key);
if(root->data!=key){
if(root == NULL){
    root = n;
}
else if(key < root->data){
    if(root->left == NULL){
        root->left = n;
        return;
    }
    else{
    insertionbst(root->left,key);
    }
}
else{
    if(root->right == NULL){
        root->right = n;
        return;
    }
    else{
    insertionbst(root->right,key);
    }
}
}
else{
    cout<<"element already exists"<<endl;
}

}

Problem i am facing - so in this code i made static variable *n because i dont want to make copies for every recursive layer but this static variable keeps same value even if i try to insert another key for example -

insertionbst(root,30);
insertionbst(root,35);

it doesn't insert key 35 in BST instead of 35 it keeps inserting 30

Thank You for Help

Maybe I'm missing something, but why don't you just allocate the node when you need it?

void insertionbst(struct node *root,int key){  
    if(root->data!=key){
        if(root == NULL){
            root = newnode(key);
        }
        else if(key < root->data){
            if(root->left == NULL){
                root->left = newnode(key);
                return;
            }
            else{
                insertionbst(root->left,key);
            }
        }
        else{
            if(root->right == NULL){
                root->right = newnode(key);
                return;
            }
            else{
                insertionbst(root->right,key);
            }
        }
    }
    else{
        cout<<"element already exists"<<endl;
    }
}

I can't see any reason why you need to make copies for every recursive layer .

I think your code has bugs, it doesn't deal correctly with the situation when root equals NULL . Maybe that situation never arises in practice, in which case you still need to clean up the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM