C++ program code is for building a binary tree, and to have, inorder, preorder & postorder tree traversal of the created binary tree

Leave a Comment
/* The Following C++ program code is for building a binary tree, and to have, inorder, preorder & postorder tree traversal of the created binary tree. The user is given 4 option to have the same as above stated & 5th one is to exit the program */

#include <iostream>
#include <stdlib.h>
using namespace std;

template <class T>
class bintree
{
bintree<T> *left;
T data;
bintree<T> *right;
public :
bintree()
{
left=right=NULL;
}
void create();
void preorder();
void inorder();
void postorder();
};


template <class T>
void bintree<T> :: create()
{
char opt;
cout << "\n Enter the element : ";
cin >> data;
cout << "\n Is there left child for " << data << " [y/n] ? : ";
cin >> opt;
if (opt=='y')
{
left = new bintree<T>;
left->create();
}
cout << "\n Is there right child for " << data << " [y/n] ? : ";
cin >> opt;
if (opt=='y')
{
right = new bintree<T>;
right->create();
}
}


template <class T>
void bintree<T> :: preorder()
{
if (this!=NULL)
{
cout << data << " ";
left->preorder();
right->preorder();
}
}


template <class T>
void bintree<T> :: inorder()
{
if (this!=NULL)
{
left->inorder();
cout << data << " ";
right->inorder();
}
}


template <class T>
void bintree<T> :: postorder()
{
if (this!=NULL)
{
left->postorder();
right->postorder();
cout << data << " ";
}
}


int main()
{
bintree<char> *x;
x=NULL;
int ch;
do
{
cout << "Binary Tree Operation Menu\n";
cout << "1. Create\n";
cout << "2. Preorder Traversal\n";
cout << "3. Inorder Traversal\n";
cout << "4. Postorder Traversal\n";
cout << "5. Exit\n\n";
cout << "Enter Your Choice [1..5] : ";
cin >> ch;
switch(ch)
{
case 1 :
x = new bintree <char>;
x->create();
break;
case 2 :
x->preorder();
break;
case 3 :
x->inorder();
break;
case 4 :
x->postorder();
break;
case 5 :
break;
default :
cout << "Invalid Choice!";
}
}while (ch!=5);
system("pause");
}


Screenshot:
C++ program code is for building a binary tree, and to have, inorder, preorder & postorder tree traversal of the created binary tree

0 comments: