简体   繁体   English

C ++复制二叉树

[英]c++ Copy a binary tree

If I use this to copy a binary tree 如果我用它来复制二叉树

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

and set overload function for = operator like this: 并为=运算符设置重载函数,如下所示:

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

then if I have two treetype element tree_1 and tree_2 . 那么如果我有两个treetype元素tree_1tree_2

When I do 当我做

tree_2 = tree_1;

I copy all the element from tree_1 to tree_2 . 我将所有元素从tree_1复制到tree_2 And at this time, I add a new node to tree_2 . 现在,我将一个新节点添加到tree_2 The tree_1 will also change. tree_1也将更改。 How can I set a new recursive copy function that makes tree_1 remains the same and only change the structure of tree_2 ? 如何设置一个新的递归复制函数,使tree_1保持不变,仅更改tree_2的结构?

you Overide only the Node Element BTNode = operator 您仅覆盖节点元素BTNode =运算符

thats way its work for the root copy when you copy the trees [tree_2 = tree_1;] 当您复制树时,多数民众赞成在根复制中起作用[tree_2 = tree_1;]

you are using the defult copy ctor that c++ provide that use bitwise copy(deep copy) you need to create a copy ctor for the tree that use foreach node the" =" operator you allreay implement 您正在使用c ++提供的使用按位复制(深层复制)的defult复制ctor,您需要为使用foreach节点的树创建一个复制ctor。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM