简体   繁体   中英

Creating a deep copy of a binary tree containing other structures in C

I have this function that's supposed to create a deep copy of a whole binary tree.

symbol_t* cloneTable(symbol_t *node) {

    if (node == NULL)
        return node;

    symbol_t *newSymbol = malloc(sizeof(symbol_t));
    newSymbol->type = node->type;
    newSymbol->key = node->key;

    if (node->value != NULL) {
        value_t *newValue = malloc(sizeof(value_t));
        newValue = node->value;
        newSymbol->value = newValue;
    }

    newSymbol->leftChild = cloneTable(node->leftChild);
    newSymbol->rightChild = cloneTable(node->rightChild);

    return newSymbol;
}

When I change value in the original table, it gets changed in the copied table, too, however.

What can I do to create a deep copy of it?

Thank you in advance for any help.

In:

    value_t *newValue = malloc(sizeof(value_t));

you allocate memory for an object. As it looks, node contains a pointer to a value object. With

    newValue = node->value;

you copy the pointer. To copy the value, use:

    *newValue = *node->value;

Now you can place the object in your new node:

    newSymbol->value = newValue;

Nb: Don't forget to set newSymbol->value= NULL; when node->value==NULL

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