我有如下定义一个树类:

class Tree {
  Tree();
private:
  TreeNode *rootPtr;
}

树节点表示节点,并具有数据,leftPtr和rightPtr。

如何创建使用拷贝构造函数树对象的副本?我想要做的事,如:

Tree obj1;
//insert nodes

Tree obj2(obj1); //without modifying obj1.

任何帮助理解!

有帮助吗?

解决方案

的伪代码:

struct Tree {
  Tree(Tree const& other) {
    for (each in other) {
      insert(each);
    }
  }

  void insert(T item);
};

具体例(改变你怎么走路的树,重要的是知道的,但展示如何拷贝构造函数有损作品,并可能会做太多别人的功课这里):

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

其他提示

这取决于你是否想要一个或<强>深 副本。假设一个深拷贝,你需要能够复制在“叶子”,挂在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。

两个基本选项:

如果你有一个迭代可用,则可以简单地遍历树中的元素和手动插入的每一个,如R.佩特说明。如果你的树类不采取明确的措施来平衡树(如AVL或红黑旋转),你会用节点的链表有效落得如此下场(即所有的左子指针将是无效的)。如果你是平衡你的树,你会切实做好平衡工作两次(因为你已经不得不弄清楚从中你复制源代码树)。

一个更快但混乱和更容易出错的解决办法是通过执行源树结构的广度优先或深度优先遍历构建拷贝自上而下。您不需要任何平衡旋转和你最终用相同的节点拓扑结构。

下面是我与二进制树中使用的另一示例。 在这个例子中,节点和树在单独的类中定义和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

复制:返回一个指向新树

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

我希望这可以帮助别人。

当你的类具有动态分配的内存,在类,你需要为新创建的对象分配内存的拷贝构造函数的指针指向。然后,你需要与任何其他指针指着初始化新分配的内存。这里是你如何需要处理具有动态分配的存储器中的类的示例:

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

您可以尝试像(未经测试)


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 ;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top