#include <iostream.h>
#include <conio.h>
class tree
{
private:
int data;
tree *left,*right;
public:
tree() {left = right = NULL;}
void insert(tree *&,int);
void inorder(tree *); //function to print tree in Inorder
void preorder(tree *); //function to print tree in Preorder
void postorder(tree *); //function to print tree in Postorder
int getdata() {return data;}
~tree()
{
delete left;
delete right;
}
};
void tree::insert(tree *&tr,int Item)
{
if(tr == NULL)
{
tr = new tree;
tr -> left = NULL;
tr -> right = NULL;
tr -> data = Item;
return;
}
tree *New,*temp;
temp = tr;
if(Item < temp -> data) //goto left
{
if(temp -> left == NULL)
{
New = new tree;
New -> left = NULL;
New -> right = NULL;
New -> data = Item;
temp -> left = New;
}
else
insert(temp -> left,Item);
}
else //goto right
{
if(temp -> right == NULL)
{
New = new tree;
New -> left = NULL;
New -> right = NULL;
New -> data = Item;
temp -> right = New;
}
else
insert(temp -> right,Item);
}
}
void tree::inorder(tree *tr)
{
if(tr != NULL)
{
inorder(tr -> left); //goto left
cout << tr -> getdata() << ' '; //print data
inorder(tr -> right); //goto right
}
}
void tree::preorder(tree *tr)
{
if(tr != NULL)
{
cout << tr -> getdata() << ' '; //print data
preorder(tr -> left); //goto left
preorder(tr -> right); //goto right
}
}
void tree::postorder(tree *tr)
{
if(tr != NULL)
{
postorder(tr -> left); //goto left
postorder(tr -> right); //goto right
cout << tr -> getdata() << ' '; //print data
}
}
int main()
{
tree *t = NULL;
int m,n;
cout << "How many numbers? ";
cin >> n;
cout << "\nEnter " << n << " Numbers\n";
for(int i = 0;i < n;i++)
{
cin >> m;
t -> insert(t,m); //Insert Items to tree
}
cout << "\nInorder : ";
t -> inorder(t);
cout << "\nPreorder : ";
t -> preorder(t);
cout << "\nPostorder : ";
t -> postorder(t);
getch();
return 0;
}
OUTPUT
How many numbers? 6
Enter 6 Numbers
16 11 19 13 22 14
Inorder : 11 13 14 16 19 22
Preorder : 16 11 13 14 19 22
Postorder : 14 13 11 22 19 16
Download Original File
Tree using C++
No comments:
Post a Comment