Home > Back-end >  How to copy a red black tree to another rb tree and remove the old one?
How to copy a red black tree to another rb tree and remove the old one?

Time:07-06

I want to copy nodes in an RB tree that satisfy a condition into another RB tree and remove the old one.

I've made these functions:

void copy_tree(node* old_root, node** copied_root) {
    if(old_root != NULL) {
        if(condition(old_root->key) == true) {
            *copied_root = insert(*copied_root, old_root);
        }

        copy_tree(old_root->left, copied_root);
        copy_tree(old_root->right, copied_root);
    }
}

node* copy_and_destroy(node* old_root) {
    node* copied_root = NULL;

    copy_tree(old_root, &copied_root);

    destroy(old_root);
    return copied_root;
}

Then, in another function, I call them:

tree = copy_and_destroy(tree);

I know that the condition, destroy, and insert functions are correct. But it gives me a segmentation fault. So, are these 2 functions correct?

CodePudding user response:

Without seeing the source to your rb_insert function, I suspect that it is adding the node pointed to by the second parameter to the new tree without copying the node. That would lead to problems while the old tree is still being traversed.

You need to remove the node from the old tree before moving it to the new tree.

If copying (rather than moving) nodes from the the old tree to the new tree, you need to create a copy of the node and add the copy to the new tree.

  •  Tags:  
  • c
  • Related