c++复制二叉树

标签 c++

如果我用它来复制一个二叉树

BTNode<ElemType>* BinaryTree<ElemType>::_Copy( BTNode<ElemType>* T){ 
    if (T == NULL){
        return NULL;
    }
    BTNode<ElemType> *p;
    p = new BTNode<ElemType>;
    p->data = T->data;
    p->lchild = _Copy(T->lchild);
    p->rchild = _Copy(T->rchild);
    return p; 
}

并像这样为 = 运算符设置重载函数:

BinaryTree& operator=(const BinaryTree &rhs){
    if (&rhs == this){
        return *this;
    }
    _Destroy (m_root);
    m_root = _Copy ( rhs.m_root);
    return *this;
}

那么如果我有两个树型元素 tree_1tree_2

当我这样做

tree_2 = tree_1;

我将所有元素从 tree_1 复制到 tree_2。 而此时,我向 tree_2 添加了一个新节点。 tree_1 也会发生变化。 如何设置一个新的递归复制函数,使 tree_1 保持不变,只改变 tree_2 的结构?

最佳答案

您仅覆盖节点元素 BTNode = operator

这就是根拷贝的工作方式 当你复制树时 [tree_2 = tree_1;]

你正在使用 c++ 提供的默认复制 ctor 使用按位复制(深复制) 你需要创建一个复制构造函数 对于使用 foreach 节点的树 “=”运算符你都可以实现

node  *Cpy( root ) { 

   if (root == NULL ) : return root;

   node *temp = new node();
   temp->data = root-> data;    

   temp->left = Cpy( root -> left);   

   temp->right = Cpy(root -> right);  

   return temp;
}

关于c++复制二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38036333/

相关文章:

c++ - glViewport undefined reference

c++ - 使用普通异常类有什么意义?

c++ - 运算符重载 = 和模板 double 值仅对 int 不起作用

c++ - 如何在 boost::regex 中找到子匹配的字符串位置

c++ - v <int> pos(MAX)v <int> tmp是非类类型 ‘__gnu_cxx::__alloc_traits<std::allocator<int>>::value_type {aka int}’ pos [i] .push_back(tmp);

c++ - CppUnit,非常简单的测试代码崩溃了,为什么?

c++ - 使用 C 和 C++ 的 Protocol Buffer

c++ - 使用 Xcode 4 配置 googletest 的正确方法是什么?

c++ - GCC -Weffc++ 警告

C++ 比较两个具有相同持续时间的 std::chrono::time_points 失败