Seg Fault on Copy Constructor of Binary Tree

So as the title states I'm getting a segmentation fault when calling the copy constructor for my binTree class. I'm not sure why here is the partial code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template<class T>
binTree<T>::binTree(const binTree<T>& bt) {
        copy(bt.root);
}


template<class T>
binTreeNode<T>* binTree<T>::copy(const binTreeNode<T>* nodePtr) {
        if(nodePtr) {
                binTreeNode<T>* newRoot = new binTreeNode<T>;
                newRoot->data = nodePtr->data;
                newRoot->left = copy(nodePtr->left);
                newRoot->right = copy(nodePtr->right);

                return newRoot;
        } else
                return NULL;
}


Any help would be appreciated
Can you show us in copy (or in the constructor) where you actually modify a data member of the class?
I was thinking this would modify it because it calls this.copy(bt.root);
1
2
3
4
template<class T>
binTree<T>::binTree(const binTree<T>& bt) {
        copy(bt.root);
} 
From the name, you would think so, but as I asked before.. where in copy is a data member of the class actually modified?
I'm probably wrong and that's the problem but I was thinking since copy returns a pointer to a new root that in turn points to the rest of the tree and this is being returned to the this pointer which is then an exact copy of the passed in binary tree. Is this wrong?
I see what your saying. copy doesn't change the root data member but I'm having trouble fixing that I tried this as well:

1
2
3
4
5
6
7
8
9
10
11
12
13
template<class T>
binTreeNode<T>* binTree<T>::copy(const binTreeNode<T>* nodePtr) {
        if(nodePtr) {
                binTreeNode<T>* newRoot = new binTreeNode<T>;
                newRoot->data = nodePtr->data;
                newRoot->left = copy(nodePtr->left);
                newRoot->right = copy(nodePtr->right);
                root = newRoot;
                delete newRoot
                return root;
        } else
                return NULL;
}
got it working, all good now...
My suggestion would be to keep the previous version of copy and add another overloaded version.

1
2
3
4
5
6
7
8
template <class T>
void binTree<T>::copy( const binTree<T>& tree )
{
    if ( tree.root )
        root = copy(tree.root) ;
    else
        root = nullptr ;
}


Then the constructor becomes:
1
2
3
4
template<class T>
binTree<T>::binTree(const binTree<T>& bt)  {
        copy(bt);
} 


Topic archived. No new replies allowed.