binary search tree assignment operator (recursion)

3.2k views Asked by At

I'm having huge troubles understanding how to implement this.

Here is the prototype and implementation I've tried thus far (please note that two of the attempts are commented out - labeled (1) and (2)

//--- ADD PROTOTYPE OF ASSIGNMENT OPERATOR HERE
 // (1) void operator=(const BST<DataType> & origList);
 // (2) BST<DataType>& BST<DataType>::operator=(const BST& origList)
BST::operator=(const BST& origList);

Currently each one results with the following error:

home\visual studio 2010\projects\bst.h(139): error C4430: missing type specifier - int assumed.

Here is the implementation of the assignment operator:

//--- Definition of operator=
template <typename DataType>
BST<DataType>& BST<DataType>::operator=(const BST& origList)
{
 if (this != &origList)
 {
    copyTree(origList.myRoot, myRoot);
    destroy(myRoot);
 }
 return *this;
}

Here is the copyTree recursive function(s):

//--- Definition of copy constructor()
template <typename DataType>
BST<DataType>::BST(const BST<DataType> & origList)
{
 copyTree(origList.myRoot, myRoot);
}

//--- Definition of copyTree()
template <typename DataType>
void BST<DataType>::copyTree(BinNodePointer origRoot, BinNodePointer & subtreeRoot)
{
 if (origRoot == 0)
    subtreeRoot = NULL;
 else
 {
    subtreeRoot = new BinNode(origRoot->data);
    copyTree(origRoot->left, subtreeRoot->left);
    copyTree(origRoot->right, subtreeRoot->right);

    //origRoot = new BinNode(subtreeRoot->data);
    //copyTree(subtreeRoot->left, origRoot->left);
    //copyTree(subtreeRoot->right, origRoot->right);
 }
}

The copy constructor works beautifully, however the assignment operator I've failed to grasp what is needed here. Any help is greatly appreciated!

P.S. You may have noticed I have "origList", it should be named "origTree" however I'm borrowing this from my previously created constructors for LinkedLists.

1

There are 1 answers

0
ravi On

This

BST<DataType>& BST<DataType>::operator=(const BST& origList)

should be

BST<DataType>& BST<DataType>::operator=(const BST<DataType>& origList)

with following declaration in the class

BST<DataType>& operator=(const BST<DataType>& origList)