Home > Back-end >  copy only some strings from a BST into another BST
copy only some strings from a BST into another BST

Time:08-27

i have a problem copying the strings contained in a BST into another BST: my aim is to copy from the original BST only the nodes with the flag usable. the problem is that after i run the function to copy those nodes the resulting BST is empty. any suggestions?

 struct node {
    char *value;
    struct node *p_left;
    struct node *p_right;
    int usable;
};

void copiaAlbero(struct node *root, struct node *alberino)
{
    if( root != NULL ) {
        copiaAlbero(root->p_left,alberino);
        if (root->usable==1)
            inserisciInAlbero(root->value, &alberino, (Compare) CmpStr);
        copiaAlbero(root->p_right, alberino);
    }
}

void inserisciInAlbero(char* key, struct node** leaf, Compare cmp) {
    int res;
    if( *leaf == NULL ) {
        *leaf = (struct node*) malloc( sizeof( struct node ) );
        (*leaf)->value = malloc( strlen (key)  1 );
        strcpy ((*leaf)->value, key);
        (*leaf)->usable=1;
        (*leaf)->p_left = NULL;
        (*leaf)->p_right = NULL;
    } else {
        res = cmp (key, (*leaf)->value);
        if( res < 0)
            inserisciInAlbero( key, &(*leaf)->p_left, cmp);
        else if( res > 0)
            inserisciInAlbero( key, &(*leaf)->p_right, cmp);
    }
}

int main() {
    struct node *head = NULL;
    struct node *alberino = NULL;
    //head gets filled and other operations assign 1 or 0 to usable
    copiaAlbero(head, alberino);
}

at the end of this code i should have all the strings of head marked with usable contained into alberino, but alberino is now empty.

CodePudding user response:

If you just look at the lines:

struct node *alberino = NULL;
copiaAlbero(head, alberino);

you know that alberino == NULL after the call to copiaAlbero. If you want to modify alberino, you must change that to copiaAlbero(head, &alberino) and of course make all the necessary changes to accommodate that.

  • Related