Writing copy constructor of a binary search tree in C A Word
Writing copy constructor of a binary search tree in C++.
A Word on the Copy Constructor and Destructor
You will need to use helper functions for your copy constructor and destructor.
These helper functions will employ similar approaches to two of the tree traversals that we have studied.
It is up to you to figure out which tree traversal would work best for the copy constructor and which tree traversal would work best for the destructor.
BinarySearchTree.h file: - I just need the code for the implementation of copy constructor.
#include <cstddef>
#include <string>
#include <assert.h>
using namespace std;
template<class bstitem>
class BinarySearchTree {
private:
struct Node {
bstitem data;
Node* left;
Node* right;
Node(bstitem newdata) :
data(newdata), left(NULL), right(NULL) {
}
};
typedef struct Node* NodePtr;
NodePtr root;
/**Private helper functions*/
void insertHelper(NodePtr root, bstitem value);
//private helper function for insert
//recursively inserts a value into the BST
void inOrderPrintHelper(NodePtr root);
//private helper function for inOrderPrint
//recursively prints tree values in order from smallest to largest
void preOrderPrintHelper(NodePtr root);
//private helper function for preOrderPrint
//recursively prints tree values in preorder
void postOrderPrintHelper(NodePtr root);
//private helper function for postOrderPrint
//recursively prints tree values in postorder
bool findHelper(NodePtr root, bstitem value);
bstitem minimumHelper(NodePtr root);
bstitem maximumHelper(NodePtr root);
NodePtr removeHelper(NodePtr root, bstitem value);
int getSizeHelper(NodePtr root);
int getHeightHelper(NodePtr root);
void destructorHelper(NodePtr root);
Node& copyHelper(NodePtr root, const BinarySearchTree &binarysearchtree);
/**Public functions*/
public:
BinarySearchTree();
//Instantiates a new Binary Search Tree
//post: a new Binary Search Tree object
~BinarySearchTree();
BinarySearchTree(const BinarySearchTree &binarysearchtree);
......
........
}
Solution
This is how the copy constructor would look like ,
#include <cstddef>
#include <string>
#include <assert.h>
using namespace std;
template<class bstitem>
class BinarySearchTree {
private:
struct Node {
bstitem data;
Node* left;
Node* right;
Node(bstitem newdata) :
data(newdata), left(NULL), right(NULL) {
}
};
typedef struct Node* NodePtr;
NodePtr root;
BinarySearchTree(const BinarySearchTree &binarysearchtree)
{
root = *binarysearchtree.root; // initializing the value of root from binarysearchtree
}
};
int main()
{
return 0;
}

