WAP to print the nodes of a tree in a each separate line.
SOLUTION
#include <iostream.h>
#include <cstdio>
#include <vector.h>
#include <unistd.h>
#include <queue.h>
using namespace std;
struct node
{
int data;
vector<node*> children;
};
//receiving input with error check
int input()
{
int num;
while(true)
{
cout<<"\n\nEnter : ";
cin>>num;
if(cin.good())
{
return num;
}
else
{
cout<<"\n\nYou Entered a non integral value\n\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
continue;
}
}
}
//for arranging childs to their parents
void create(node* Node, int num1)
{
int i=0,y=0;
int num=num1;
int val;
int curr=1;
int flag=0;
for(y=0; y < num; y++)
{
if(curr < num)
{
cout<<"\n\nEnter No of children for node " << y<<" :";
val=input();
while(val > 0)
{
Node[y].children.push_back(&Node[curr++]);
val--;
}
}
else
{
flag=1;
break;
}
}
}
//printing tree in the required form
void printtree(node * root)
{
queue<node*> q;
int curr_lev_counter,next_lev_counter;
q.push(root);
curr_lev_counter=1;
next_lev_counter=0;
while(!q.empty())
{
node * nd = q.front();
q.pop();
curr_lev_counter--;
cout<data<<" ";
for(int i=0; i < nd->children.size(); i++)
{
q.push(nd->children[i]);
next_lev_counter++;
}
if(curr_lev_counter == 0)
{
curr_lev_counter=next_lev_counter;
next_lev_counter=0;
cout<<endl;
}
}
}
int main()
{
int num;
int i=0;
cout<<"\n\nHow many nodes you want to enter in the tree : ";
num=input();
if(num > 0)
{
node Node[num];
cout<<"\n\n Enter Values of nodes \n\n";
for( i=0; i < num; i++)
{
Node[i].data = input();
}
create(Node,num);
cout<<"\n\nThe tree looks like : \n\n";
printtree(Node);
cout<<endl<<endl;
}
else
{
cout<<"\n\nThe tree is empty\n\n ";
}
}
No comments:
Post a Comment