I wrote this code over night for a little project that my friend and I have been working on. This class template was created over a year ago during as a class assignment for C++ programming. I recently reviewed this program and I saw that I created multiple instances of my classes in order to print out different data types in the output.
This is not efficient coding at all and I know it can be prone to bugs. However, would anyone consider making abstract classes instead? Please given me an opinion on how I should change this code in order for it to be efficient and reduce the creation of the same class.
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
template<class T>
class BinaryTree
{
struct Node
{
T data;
Node* lChildptr;
Node* rChildptr;
Node(T dataNew)
{
data = dataNew;
lChildptr = NULL;
rChildptr = NULL;
}
};
private:
Node* root;
void Insert(Node* newData, Node* &theRoot)
{
if(theRoot == NULL)
{
theRoot = newData;
return;
}
else if(newData->data < theRoot->data)
Insert(newData, theRoot->lChildptr);
else
Insert(newData, theRoot->rChildptr);;
}
void insertnode(T item)
{
Node *newData;
newData= new Node(item);
Insert ( newData, root);
}
void PrintTree(Node* &theRoot)
{
if(theRoot)
{
cout << theRoot->data << endl;
PrintTree(theRoot->lChildptr); //<< The error is here
PrintTree(theRoot->rChildptr);
}
}
public:
BinaryTree()
{
root = NULL;
}
void AddItem(T item)
{
insertnode(item);
}
void PrintTree()
{
PrintTree(root);
}
};
int main()
{
BinaryTree<string> *tree = new BinaryTree<string>();
BinaryTree<int> *myBT = new BinaryTree<int>();
BinaryTree<double> *mydouble = new BinaryTree<double>();
BinaryTree<char> *mychar = new BinaryTree<char>();
tree->AddItem("Erick");
myBT->AddItem(7);
mydouble->AddItem(9.99999);
mychar->AddItem('@');
tree->PrintTree();
myBT->PrintTree();
mydouble->PrintTree();
mychar->PrintTree();
system ( "pause");
}