Search code examples
c++c++11binary-treedeep-copy

Deep copy of binary tree


I have this tree with different types of nodes that I need to do a deep copy on. The hierarchy looks something like this:

class AllNodes
{
    //this is a purely virtual base class
};
class TreeNode : public AllNodes
{
    AllNodes *rChild, *lChild;
};
class LeefNode : public AllNodes
{
    int value;
};

The problem is that when I want to do a deep copy of the entire tree, I don't know what nodes will have children and what nodes will have values. I've tried this, but it wont work (for obvious reasons):

void AllNodes::deepCopy(AllNodes* &copied, AllNodes* o)
{
    if(o->rChild == nullptr)
        copied->rChild = nullptr;
    else
    {
        copied->rChild = o->rChild;   
        deepCopy(copied->rchild, o->rChild);
    }

    if(o->lChild == nullptr)
        copied->lChild = nullptr;
    else
    {
        copied->lChild = o->lChild;
        deepCopy(copied->lChild, o->lChild);
    }
}

Does anyone have some ideas of how to accomplish this?


Solution

  • Create a virtual method and implement it in TreeNode and LeafNode.

    class AllNodes
    {
        //this is a purely virtual base class
        virtual AllNodes* copy() const = 0;
    };
    class TreeNode : public AllNodes
    {
        AllNodes* rChild, lChild;
        virtual AllNodes* copy() const {
             TreeNode *n = new TreeNode;
             n->rChild = rChild->copy();
             n->lChild = lChild->copy();
             return n;
        }
    };
    class LeafNode : public AllNodes
    {
        int value;
        virtual AllNodes* copy() const {
             LeafNode *n = new LeafNode;
             n->value = value;
             return n;
        }
    };
    

    (Just a draft)