Binary Search Tree Insertion and Traversing by Pre_Order and In_Order

#include<iostream>
#include<conio.h>
using namespace std;
struct node
{
int info;
node *left,*right;
}*root=NULL,*stack[50];
int size=0;
int insert()
{
size++;
int x;
cout<<"Enter info part: ";
cin>>x;
node *temp=new node;
temp->info=x;
int n=2;
    if(root==NULL)
{
   root=temp;
temp->left=NULL;
temp->right=NULL;
return 1;
}
node *ptr=new node;
node *ctr=new node;
ctr=NULL;
ptr=root;
while(ptr!=NULL)
{
if(ptr->info>x)
{
ptr=ptr->left;
}
else if(ptr->info==x)
{  
cout<<"Item already in list!\n";
int x=0;
return x;
}
else
{
ptr=ptr->right;
}
}
ptr=root;
while(ptr!=NULL)
{
if(ptr->info>x)
{
ctr=ptr;
ptr=ptr->left;
}
else
{
ctr=ptr;
ptr=ptr->right;
}
}
if(ctr->info>x)
{
ctr->left=temp;
temp->left=NULL;
temp->right=NULL;
}
else
{
ctr->right=temp;
temp->right=NULL;
temp->left=NULL;
}
}
int disp_post()
{
int n=0;
cout<<"\n\nPost_Order: ";
stack[0]=NULL;
node *ntr=new node;
ntr=root;
while(ntr!=NULL)
{
cout<<ntr->info<<"\t";
if(ntr->right!=NULL)
{
n=n+1;
stack[n]=ntr->right;;
}
if(ntr->left!=NULL)
ntr=ntr->left;
else
{
ntr=stack[n];
n=n-1;
}
}

}
int disp_in()
{
int n=0;
cout<<"\n\nPre_Order: ";
stack[0]=NULL;
node *ntr=new node;
ntr=root;
repeat:
{
while(ntr!=NULL)
{
n=n+1;
stack[n]=ntr;
ntr=ntr->left;
}
ntr=stack[n];
n=n-1;
while(ntr!=NULL)
{
cout<<"\t"<<ntr->info;
if(ntr->right!=NULL)
{
ntr=ntr->right;
goto repeat;
}
ntr=stack[n];
n=n-1;
}
}
}
int main()
{
root=NULL;
int ch;
while(1)
{
cout<<"\n1. Insert\n2. Display in post_Order\n3. Display in In_Order\n4. Exit\nChoice: ";
cin>>ch;
switch(ch)
{
case 1:
insert();
break;
case 2:
disp_post();
break;
case 3:
disp_in();
break;
case 4:
return 0;
default:
cout<<"Warning! Invlid choice!\n";
}
}
getch();
return 0;
}
Output:

Popular posts from this blog

Shutdown Pc

Ellipse using OpenGl

String Comparisons