Google Ads

Friday, September 4, 2009

PRINTING NODE DETAILS IN LEVEL WISE

PRINTING NODE DETAILS IN LEVEL WISE


#include”iostream.h”
#include”conio.h”
#include”malloc.h”
#include”math.h”
#include”process.h”
class binary
{
private:
struct node
{
int data;
node *left,*right;
}*root;
node *queue[30];
int rear,front,size;
public:
void insert(node *);
struct node *remove();
int qnotempty();
void create();
void traverse();
};

void binary::insert(node *temp)
{
queue[rear++]=temp;
}

struct binary::node *binary::remove()
{
node *temp=queue[front];
front++;
if(front==rear)
{
front=rear=0;
}
return temp;
}

int binary::qnotempty()
{
if(front==0 && rear==0)
{
return(0);
}
else
{
return(1);
}
}

void binary::create()
{
int i=1;
node *new1, *temp;
root=NULL;
rear=front=0;
cout<<"Enter the size of the tree\t";
cin>>size;
new1=new node();
new1->left=new1->right=NULL;
cout<<"Enter the"< cin>>new1->data;
root=new1;
insert(root);
//insert(root);
for(i=2;i<=size;i++)
{
temp=remove();
new1= new node();
new1->left=new1->right=NULL;
cout<<"Enter the "< cin>>new1->data;
if(temp->left==NULL)
{
temp->left=new1;
}
else
if(temp->right==NULL)
{
temp->right=new1;
}
insert(new1);
//insert(new1);
}
}
void binary::traverse()
{
int level=0;
int count=0;
rear=front=0;
node *temp=root;
insert(temp);
cout<<"\nLevel"< do
{
temp=remove();
if(temp!=NULL)
{
cout<<"\t"<data;
insert(temp->left);
//insert(temp->right);
}
count++;
if(pow(2,level)==count && pow(2,level+1) <= size)
{
level++;
cout< count=0;
}
}while(qnotempty()==1);
}

void main()
{
int ch;
binary b;
clrscr();
for(;;)
{
cout<<"\n\n1.Create\n2.LevelWise Traverse\n3.Exit\n";
cout<<"Enter choice\n";
cin>>ch;
switch(ch)
{
case 1:
b.create();
break;
case 2:
b.traverse();
break;
case 3:
exit(0);
}
}
}






OUTPUT:

PRINTING NODE DETAILS IN LEVEL WISE



1.Create
2.LevelWise Traverse
3.Exit
Enter choice
1
Enter the size of the tree 6
Enter the1Element 34
Enter the 2Element 54
Enter the 3Element 67
Enter the 4Element 23
Enter the 5Element 43
Enter the 6Element 99


1.Create
2.LevelWise Traverse
3.Exit
Enter choice
2

Level0 34

Level1 54 67

Level2 23 43 99


1.Create
2.LevelWise Traverse
3.Exit
Enter choice
3

No comments:

Post a Comment