Wednesday, 8 January 2020

Create a binary Tree and show level wise traversing in C++



Create a Binary Tree  and show level wise traversing in C++



#include<iostream>
#include<stdio.h>
#include<queue>
using namespace std;

class Node
{
char data[10];
Node *left;
Node * right;
friend class Tree;
};
class Tree
{
public:
Node *temp,*root;
Tree();
void create();
void insert(Node *root,Node *New);
void display();
};
Tree::Tree()
{
temp=NULL;
root=NULL;
}
void Tree::create()
{
temp=new Node;
temp->left=temp->right=NULL;
cout<<"\nEnter the Data: ";
cin>>temp->data;
if(root==NULL)
{
root=temp;
}
else
{
insert(root,temp);
}
}
void Tree::insert(Node *root,Node *temp)
{
char ans;
cout<<"Where to insert "<<temp->data<<" at Left(L) OR Right(R) "<<root->data<<"? ";
cin>>ans;
if(ans=='L'||ans=='l')
{
if(root->left==NULL)
root->left=temp;
else
insert(root->left,temp);
}
else
{
if(root->right==NULL)
root->right=temp;
else
insert(root->right,temp);
}
}
void Tree :: display()
{
queue<Node *> q;
if(root==NULL)
{
cout<<"NULL Tree";
return;
}
q.push(root);
while(!q.empty())
{
Node *temp = q.front();
q.pop();
cout <<temp->data<<"\t" ;
if(temp->left){  q.push(temp->left); }
if(temp->right){  q.push(temp-> right); }
}
}
int main()
{
Tree tr;
int i=0;
do
{
if(i==0)
{
cout<<"\n***Chapter Data***";
tr.create();
i++;
}
if(i==1||i==2)
{
cout<<"\n***Section Data***";
tr.create();
i++;
}
if(i==3||i==4||i==5||i==6)
{
cout<<"\n***Sub-Section Data***";
tr.create();
i++;
}
if(i==7)
{
cout<<"\nLevel wise Tree is:";
tr.display();
break;
}
}while(1);
}


Output:

***Chapter Data***
Enter the Data: 10

***Section Data***
Enter the Data: 5
Where to insert 5 at Left(L) OR Right(R) 10? L

***Section Data***
Enter the Data: 7
Where to insert 7 at Left(L) OR Right(R) 10? R

***Sub-Section Data***
Enter the Data: 1
Where to insert 1 at Left(L) OR Right(R) 10? L
Where to insert 1 at Left(L) OR Right(R) 5? L

***Sub-Section Data***
Enter the Data: 12
Where to insert 12 at Left(L) OR Right(R) 10? R
Where to insert 12 at Left(L) OR Right(R) 7? L

***Sub-Section Data***
Enter the Data: 14
Where to insert 14 at Left(L) OR Right(R) 10? L
Where to insert 14 at Left(L) OR Right(R) 5? R

***Sub-Section Data***
Enter the Data: 66
Where to insert 66 at Left(L) OR Right(R) 10? L
Where to insert 66 at Left(L) OR Right(R) 5? R
Where to insert 66 at Left(L) OR Right(R) 14? L

Level wise Tree is:10 5 7 1 14 12 66

1 comment:

  1. I note that we don't need stdio.h header file since we are not using printf, scanf etc.

    Why are you not using references instead of pointers?

    ReplyDelete

Stack and Queue as ADT in C++

Stack as ADT The functions associated with stack are: empty()  – Returns whether the stack is empty size()  – Returns the size o...