binarytree.cpp

Code:

#include <iostream>
using namespace std;
template <class T>
class BinaryTree{
public:
BinaryTree(T);
BinaryTree<T>* insert(T, BinaryTree<T>*);
void inorder();
int countNodes(BinaryTree<T>*);
BinaryTree<T>* reverse(BinaryTree<T>*);
friend ostream& operator<<(ostream&, const BinaryTree<T>*);
private:
T data;
BinaryTree* left;
BinaryTree* right;
};
template <class T>
BinaryTree<T>::BinaryTree(T x){
data=x;
left=NULL;
right=NULL;
}
template <class T>
BinaryTree<T>* BinaryTree<T>::insert(T x, BinaryTree<T>* bt ){
if( bt == NULL ){
bt = new BinaryTree<T>(x);
}
else if( x < bt->data ){
bt->left = insert( x, bt->left );
}
else if( x > bt->data ){
bt->right = insert( x, bt->right );
}
return bt;
}
template <class T>
void BinaryTree<T>::inorder(){
if(this!=NULL){
this->left->inorder();
cout << this->data << endl;
this->right->inorder();
}
}
template <class T>
int BinaryTree<T>::countNodes(BinaryTree<T>* bt) {
if ( bt == NULL ) return 0;
else {
int count = 1;
count += countNodes(bt->left);
count += countNodes(bt->right);
return count;
}
}
template <class T>
BinaryTree<T>* BinaryTree<T>::reverse(BinaryTree<T>* bt){
if(bt!=NULL){
BinaryTree<T>* temp = bt->left;
bt->left=bt->right;
bt->right=temp;
}
return bt;
}
**template <class T>
ostream& operator<<(ostream& out, const BinaryTree<T>* bt){
out << bt->data;
return out;**
}

main.cpp

Code:

#include <iostream>
#include "binarytree.cpp"
using namespace std;
int main(){
int choice;
int size;
bool play=true;
BinaryTree<int> *bn = NULL;
while(play){
cout << "Menu Display" << endl << "-------------" << endl << "1) Enter Data" << endl << "2) Print Tree" << endl
<< "3) Reverse Tree" << endl << "4) Quit" << endl;
cout << "Enter your choice: ";
cin >> choice;
if(choice==1){
int num;
cout << "Enter data for tree: ";
cin >> num;
bn = bn->insert(num,bn);
}
** if(choice==2){
size=bn->countNodes(bn);
cout << "Tree size = " << size << endl << "-------------" << endl;
cout << bn;
}**
if(choice==3){
bn = bn->reverse(bn);
}
if(choice==4){
play=false;
}
}
system("PAUSE");
return 0;
}