二进制树的深拷贝

时间:2014-09-02 09:14:15

标签: c++ c++11 binary-tree deep-copy

我有这个树有不同类型的节点,我需要进行深层复制。层次结构看起来像这样:

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

问题在于,当我想要对整个树进行深层复制时,我不知道哪些节点会有子节点以及哪些节点将具有值。我试过这个,但它不起作用(原因很明显):

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);
    }
}

有没有人对如何做到这一点有一些想法?

2 个答案:

答案 0 :(得分:5)

创建一个虚方法并在TreeNode和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;
    }
};

(只是选秀)

答案 1 :(得分:2)

这是多态行为(根据对象的具体类型创建深层副本)。因此,它应该在整个节点层次结构中的虚函数中实现。

执行深层复制的功能通常称为clone:

class AllNodes
{
    //this is a purely virtual base class
public:
    virtual AllNodes* clone() = 0;
};

class TreeNode : public AllNodes
{
    AllNodes *rChild, *lChild; // you skipped declaring lChild as a pointer
public:
    virtual AllNodes* clone() override // recursive implementation for child nodes
    {
         return new TreeNode{
             rChild ? rChild->clone() : nullptr,
             lChild ? lChild->clone() : nullptr }; // assume existence of this
                                                   // constructor
    }
};

class LeafNode : public AllNodes
{
    int value;
public:
    virtual AllNodes* clone() override
    {
        return new LeafNode{ value }; // assume existence of this constructor
    }
};

客户端代码(整个树的深层副本):

AllNodes *original; // filled in elsewhere
AllNodes *deepCopy = original->clone();