Saturday, December 7, 2013

Q. Connect nodes of tree at same level with next pointer


Here  we  have  a  single  difference  in  structure  of  a  link  list  and  that  is  we  have  next  node  in  this  and  we  have  to  connect  the


Like  in  the  above  tree  we  need  to  connect

2->3
4->5->6
7->8

Here  is  the  working  code  below  for  this.  It  is  basically  a  level  order  traversal  only

#include<iostream.h>
#include<queue>
#include<vector>
using namespace std;
struct node
{
    int info;
    struct node* left;
    struct node* right;
    struct node* next;
};
node* newNode(int data)
{
    struct node* temp = new node;
    temp->info = data;
    temp->left = NULL;
    temp->right = NULL;
    temp->next=NULL;
  return (temp);
}
int breakCondition(vector<node*> temp)
{
for(int k=0;k<temp.size();k++)
{
node* temp1=temp.at(k);
if(temp1->left || temp1->right)
return 1;
}
return 0; }

int main()
{
struct node *n1 = newNode(1);
    n1->left        = newNode(2);
    n1->right       = newNode(3);
    n1->left->left  = newNode(4);
    n1->left->right = newNode(5);
    n1->right->left  = newNode(6);
    n1->left->right->left = newNode(7);
    n1->left->right->right = newNode(8);
 
    std::queue<node*> Q1;
    vector<node*> v;
    v.push_back(n1);
    Q1.push(n1);
 
 
while(1)
{
if(breakCondition(v)==0)
break;
v.clear();
    while(!Q1.empty())
    {
     node* temp=Q1.front();
   
     if(temp->left!=NULL)
     v.push_back(temp->left);
if(temp->right!=NULL)
     v.push_back(temp->right);
   
     Q1.pop();
   }
 
 
   for(int k=0;k<v.size();k++)
  {
node* temp2=v.at(k);
Q1.push(temp2);
cout<<temp2->info;   }
  cout<<endl;
    for(int k=0;k<v.size()-1;k++)
  {
node* temp=v.at(k);
node*temp1=v.at(k+1);
temp->next=temp1;    }
 
}
node*temp=n1->left->right->left;
temp=temp->next;
cout<<"Next  pointer  to  temp  is"<<"  "<<temp->info<<endl;
return 0;
}

No comments:

Post a Comment