Tuesday, 9 January 2018

data structure

A program that add new node if the all node in the 





#include <iostream>
#include<queue>
using namespace std;
struct BTNode{
int data;
BTNode *left;
BTNode *right;
};BTNode *root;

BTNode* getnewNode(int a){

BTNode *n=new BTNode;

if(a % 2==0)
{
cout<<"num is even: not added"<<endl;
}else
{

n->data=a;
}
n->right=NULL;
n->left=NULL;
return n;


}
BTNode* insertNode (BTNode* r,int d){
if(r==NULL)
{
r=getnewNode(d);


}else
{
if( d<=r->data)
{
r->left=insertNode(r->left,d);
}else
{
r->right=insertNode(r->right,d);
}
return r;

}

}
void in_orderdisplay( BTNode* r)
{
if(r==NULL)
{
return;

}
in_orderdisplay(r->left);
cout<<r->data;
in_orderdisplay(r->right);
}
void pre_orderdisplay(BTNode* r)
{
if(r==NULL)
{
return ;

}
cout<<r->data<<endl;
pre_orderdisplay(r->left);
pre_orderdisplay(r->right);
}
 void post_orderdisplay(BTNode* r)
{
if(r==NULL)
{
return;
}
post_orderdisplay(r->left);
post_orderdisplay(r->right);
cout<<r->data;

}
void level_orderdisplay(BTNode* r){
if(r==NULL)
{

return;

}
queue<BTNode*> Q;
Q.push(r);
while(!Q.empty())
{
BTNode* temp=Q.front();
cout<<temp->data;
if(temp->left!=NULL)
{
Q.push(temp->left);
}
if( temp->right!=NULL)
{
Q.push(temp->right);

}
Q.pop();
}


}

int main()
{
int choice,a ;
root=NULL;

char ch='y';
while(ch='y')
{

cout<<"enter 1 to add node "<<endl;
cout<<"enter 2 to display"<<endl;
cout<<"enter 3 to inorder dispaly"<<endl;
cout<<"enter 4 to postorder dispaly"<<endl;
cout<<"enter 5 to level wise display"<<endl;
cin>>choice;
switch(choice)
{
case 1:
cout<<"enter value"<<endl;
cin>>a;
root=insertNode(root,a);
break;
case 2:
pre_orderdisplay(root);
break;
case 3:
in_orderdisplay(root);
break;
case 4:
post_orderdisplay(root);
break;
case 5:
level_orderdisplay(root);
break;
default:
break;

}
cout<<"prees y to continue"<<endl;
cout<<"press n to exist"<<endl;
cin>>ch;
}
}



No comments:

Post a Comment