Search code examples
crecursiondata-structuresb-tree

how to access variable values of previous call from current call in recursion


I am making a recursive function to insert value in a btree. Before moving to the next node, I save the address of that node(pds_parent) so that I always have a pointer pointing to the parent.

But pds_parent gets initialized every time(node *pds_parent;), so I am not access the parent of a node, How I can access the parent of a node while going into recursion i.e accessing the child nodes and going out of recursion i.e moving back to parent.

void insertion(node *pds, int item){
    node *pds_parent;
    if(pds[0]->limit==0)
    {
        pds[1]->value=item;
        pds[0]->limit++;
        return 1;
    }
    int loc=b_search(pds,item,1,limit)
    if(pds[0]->is_leaf)
    {
        if(pds[0]->limit==2)
        {
            if(loc==0)
            {
                int value=pds[1]->value;
            }
            else if(loc==1)
            {
                int value=item
            }
            else
            {

                int value=pds[2]->value;
            }
            splitting(pds_parent,value,pds);
        }
        else
        {

            pds[(pds[0]->limit+1)]->value=item;
            if(loc==limit)
            {
               pds[(pds[0]->limit+1)].nextIndex=-1;
               pds[loc].nextIndex=limit+1;
            }
            else
            {
               pds[(pds[0]->limit+1)].nextIndex=loc+1;
               pds[loc].nextIndex=limit+1;
            }
            pds[0]->limit++;
            return 1;
        }
    }
    else
    {
        pds_parent=pds;
        insertion(pds[loc]->c,int item);
    }
}

Solution

  • If you want a variable to be shared across function calls, you should use static keyword. You can read more about it here .

    First, initialize it while declaring:

    static node *pds_parent = NULL;

    This means that the first value of the pointer variable will be NULL. Before every recursive call, set it with the value of the current node being visited. Also, only use it if it's not NULL.

    EDIT: I shall also add that I would rather change the function signature to void insertion(node *pds, int item, node *parent) and call it with a NULL the first time. Of course, having to use NULL is not pretty but you can wrap it. This is what kiran Biradar suggested, I assume.