Joh*_*son 1 c++ binary-tree deep-copy c++11
我有这个树与不同类型的节点,我需要进行深层复制.层次结构看起来像这样:
class AllNodes
{
//this is a purely virtual base class
};
class TreeNode : public AllNodes
{
AllNodes *rChild, *lChild;
};
class LeefNode : public AllNodes
{
int value;
};
Run Code Online (Sandbox Code Playgroud)
问题是,当我想要对整个树进行深层复制时,我不知道哪些节点会有子节点以及哪些节点将具有值.我试过这个,但它不会工作(原因很明显):
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);
}
}
Run Code Online (Sandbox Code Playgroud)
有没有人对如何实现这一点有一些想法?
创建一个虚方法并在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;
}
};
Run Code Online (Sandbox Code Playgroud)
(只是一个草案)
| 归档时间: |
|
| 查看次数: |
2135 次 |
| 最近记录: |