#include< cstdlib >
#include< string >
using namespace std;
struct tree
{
int info;
tree *Left, *Right;
};
tree *root;
class Binary_tree
{
string path;
public:
Binary_tree();
void insert1(int);
tree *insert2(tree *, tree *);
void search(int);
void pretrav(tree *);
void intrav(tree *);
void posttrav(tree *);
};
Binary_tree::Binary_tree()
{
root = NULL;
}
tree* Binary_tree::insert2(tree *temp,tree *newnode)
{
if(temp==NULL)
{
temp=newnode;
}
else if(temp->info < newnode->info)
{
insert2(temp->Right,newnode);
if(temp->Right==NULL)
temp->Right=newnode;
}
else
{
insert2(temp->Left,newnode);
if(temp->Left==NULL) temp->Left=newnode;
}
return temp;
}
void Binary_tree::insert1(int n)
{
tree *temp=root,*newnode;
newnode=new tree;
newnode->Left=NULL;
newnode->Right=NULL;
newnode->info=n;
root=insert2(temp,newnode);
}
void Binary_tree::pretrav(tree *t = root)
{
if(root == NULL)
{
cout<<"Nothing to display";
}
else if(t != NULL)
{
cout<< t->info<<" ";
pretrav(t->Left);
pretrav(t->Right);
}
}
void Binary_tree::intrav(tree *t = root)
{
if(root==NULL)
{
cout<<"Nothing to display";
}
else if(t!=NULL)
{
intrav(t->Left);
cout<< t->info<<" ";
intrav(t->Right);
}
}
void Binary_tree::posttrav(tree *t = root)
{
if(root==NULL)
{
cout<<"Nothing to display";
}
else if(t!=NULL)
{
posttrav(t->Left);
posttrav(t->Right);
cout<< t->info<<" ";
}
}
void Binary_tree::search(int key)
{
tree *temp=root,*parent=root;
path = "";
if(temp==NULL)
{
cout<<"The tree is empty"<< endl;
}
else
{
path = "root";
while(temp!=NULL && temp->info!=key)
{
parent=temp;
if(temp->info< key)
{
temp=temp->Right;
path += "->Right";
}
else
{
temp=temp->Left;
path += "->Left";
}
}
}
if(temp==NULL)
{
cout<<"Key not found!";
}
else
{
cout<<"Key is found\n";
cout<<"Paht is: ";
cout<< path;
}
}
int main()
{
Binary_tree bt;
int choice, n, key;
while(1)
{
cout<<"\n\t1. Insert\n\t2. Search\n\t3. Preorder Traversal\n\t4. Inorder Treversal\n\t5. Postorder Traversal\n\t6. Exit"<< endl;
cout<<"Enter your choice: ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter item: ";
cin>>n;
bt.insert1(n);
break;
case 2:
cout<<"Enter element to search: ";
cin>>key;
bt.search(key);
break;
case 3:
cout<< endl;
bt.pretrav();
break;
case 4:
cout<< endl;
bt.intrav();
break;
case 5:
cout<< endl;
bt.posttrav();
break;
case 6:
exit(0);
}
}
return 0;
}
No comments:
Post a Comment