我有一棵树,上面有不同类型的节点,需要对它们进行深层复制。层次结构如下所示:
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);
}
}
有人对如何实现这一目标有想法吗?
最佳答案
创建一个虚拟方法并在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;
}
};
(只是草稿)
关于c++ - 二叉树的深层拷贝,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25619850/