我有一个具有以下定义的Tree类:
class Tree {
Tree();
private:
TreeNode *rootPtr;
}
TreeNode表示一个节点并具有数据,leftPtr和rightPtr。
如何使用复制构造函数创建树对象的副本?我想做点什么:
Tree obj1;
//insert nodes
Tree obj2(obj1); //without modifying obj1.
感谢任何帮助!
答案 0 :(得分:8)
的伪代码:
struct Tree {
Tree(Tree const& other) {
for (each in other) {
insert(each);
}
}
void insert(T item);
};
具体的例子(改变你走树的方式很重要,但是会减少显示复制ctor如何工作,并且可能在这里做了太多的人的作业):
#include <algorithm>
#include <iostream>
#include <vector>
template<class Type>
struct TreeNode {
Type data;
TreeNode* left;
TreeNode* right;
explicit
TreeNode(Type const& value=Type()) : data(value), left(0), right(0) {}
};
template<class Type>
struct Tree {
typedef TreeNode<Type> Node;
Tree() : root(0) {}
Tree(Tree const& other) : root(0) {
std::vector<Node const*> remaining;
Node const* cur = other.root;
while (cur) {
insert(cur->data);
if (cur->right) {
remaining.push_back(cur->right);
}
if (cur->left) {
cur = cur->left;
}
else if (remaining.empty()) {
break;
}
else {
cur = remaining.back();
remaining.pop_back();
}
}
}
~Tree() {
std::vector<Node*> remaining;
Node* cur = root;
while (cur) {
Node* left = cur->left;
if (cur->right) {
remaining.push_back(cur->right);
}
delete cur;
if (left) {
cur = left;
}
else if (remaining.empty()) {
break;
}
else {
cur = remaining.back();
remaining.pop_back();
}
}
}
void insert(Type const& value) {
// sub-optimal insert
Node* new_root = new Node(value);
new_root->left = root;
root = new_root;
}
// easier to include simple op= than either disallow it
// or be wrong by using the compiler-supplied one
void swap(Tree& other) { std::swap(root, other.root); }
Tree& operator=(Tree copy) { swap(copy); return *this; }
friend
ostream& operator<<(ostream& s, Tree const& t) {
std::vector<Node const*> remaining;
Node const* cur = t.root;
while (cur) {
s << cur->data << ' ';
if (cur->right) {
remaining.push_back(cur->right);
}
if (cur->left) {
cur = cur->left;
}
else if (remaining.empty()) {
break;
}
else {
cur = remaining.back();
remaining.pop_back();
}
}
return s;
}
private:
Node* root;
};
int main() {
using namespace std;
Tree<int> a;
a.insert(5);
a.insert(28);
a.insert(3);
a.insert(42);
cout << a << '\n';
Tree<int> b (a);
cout << b << '\n';
return 0;
}
答案 1 :(得分:5)
这取决于您是否需要shallow or deep副本。假设有一个深层副本,你需要能够复制挂在TreeNode
对象上的“叶子”中的任何内容;理想情况下,功能应该在TreeNode
中(除非Tree
是TreeNode
的朋友类,您已经设计为非常熟悉其实现,当然通常就是这样; - )。假设像......:
template <class Leaf>
class TreeNode {
private:
bool isLeaf;
Leaf* leafValue;
TreeNode *leftPtr, *rightPtr;
TreeNode(const&Leaf leafValue);
TreeNode(const TreeNode *left, const TreeNode *right);
...
然后你可以添加一个
public:
TreeNode<Leaf>* clone() const {
if (isLeaf) return new TreeNode<Leaf>(*leafValue);
return new TreeNode<Leaf>(
leftPtr? leftPtr->clone() : NULL,
rightPtr? rightPtr->clone() : NULL,
);
}
如果Tree
正在处理这种级别的功能(作为朋友类),那么显然你将拥有完全等效的但是将节点克隆为显式arg。
答案 2 :(得分:2)
两个基本选项:
如果你有一个可用的迭代器,你可以简单地遍历树中的元素并手动插入每个元素,如R. Pate描述的那样。如果您的树类没有采取明确的措施来平衡树(例如AVL或红黑旋转),那么您将以这种方式有效地使用链接的节点列表(也就是说,所有左子节点指针都将为null )。如果你在平衡你的树,你将有效地进行两次平衡工作(因为你已经必须在你正在复制的源树上找到它)。
更快,但更容易出错且更容易出错的解决方案是通过对源树结构进行广度优先或深度优先遍历来自上而下构建副本。您不需要任何平衡旋转,并且最终会得到相同的节点拓扑。
答案 3 :(得分:1)
这是我用二叉树的另一个例子。
在此示例中,节点和树在单独的类中定义,copyHelper
递归函数帮助copyTree
函数。代码不完整,我试图只提供了解函数如何实现的必要条件。
<强> copyHelper 强>:
void copyHelper( BinTreeNode<T>* copy, BinTreeNode<T>* originalNode ) {
if (originalTree == NULL)
copy = NULL;
else {
// set value of copy to that of originalTree
copy->setValue( originalTree->getValue() );
if ( originalTree->hasLeft() ) {
// call the copyHelper function on a newly created left child and set the pointers
// accordingly, I did this using an 'addLeftChild( node, value )' function, which creates
// a new node in memory, sets the left, right child, and returns that node. Notice
// I call the addLeftChild function within the recursive call to copyHelper.
copyHelper(addLeftChild( copy, originalTree->getValue()), originalTree->getLeftChild());
}
if ( originalTree->hasRight() ) { // same with left child
copyHelper(addRightChild(copy, originalTree->getValue()), originalTree->getRightChild());
}
} // end else
} // end copyHelper
copy :返回指向新树的指针
Tree* copy( Tree* old ) {
Tree* tree = new Tree();
copyHelper( tree->root, oldTree->getRoot() );
// we just created a newly allocated tree copy of oldTree!
return tree;
} // end copy
用法:
Tree obj2 = obj2->copy(obj1);
我希望这有助于某人。
答案 4 :(得分:0)
当您的类具有指向动态分配的内存的指针时,在该类的复制构造函数中,您需要为新创建的对象分配内存。然后你需要用指向的其他指针初始化新分配的内存。下面是一个示例,说明如何处理具有动态分配内存的类:
class A
{
int *a;
public:
A(): a(new int) {*a = 0;}
A(const A& obj): a(new int)
{
*a = *(obj.a);
}
~A() {delete a;}
int get() const {return *a;}
void set(int x) {*a = x;}
};
答案 5 :(得分:0)
您可以尝试类似(未经测试的)
class Tree {
TreeNode *rootPtr;
TreeNode* makeTree(Treenode*);
TreeNode* newNode(TreeNode* p)
{
TreeNode* node = new Treenode ;
node->data = p->data ;
node->left = 0 ;
node->right = 0 ;
}
public:
Tree(){}
Tree(const Tree& other)
{
rootPtr = makeTree(other.rootPtr) ;
}
~Tree(){//delete nodes}
};
TreeNode* Tree::makeTree(Treenode *p)
{
if( !p )
{
TreeNode* pBase = newNode(p); //create a new node with same data as p
pBase->left = makeTree(p->left->data);
pBase->right = makeTree(p->right->data);
return pBase ;
}
return 0 ;
}