how can I code using the approach of queue<pair<node*,int>>
please share the code
In bfs using queue
this was use when we have to print each in the next line
hello @shashankmaheshwari054
u are asking code for level order travesal which print each level in seprate line right?
yes but using queue of pair
what information u will store in that pair?
isnt it queue<Node *> will work fine?
queue<pair<node*,int>> first is for the node and the second one is for the level
ok ok got it.
pls wait . i need to code it first .will share with u soon
check this->
void print(node *root){
int previouslevel=-1;
queue< pair<node*,int> > q;
q.push({root,0});
while(!q.empty()){
pair<node*,int> cur=q.front();
q.pop();
int currentNode=cur.first;
int currentlevel=cur.second;
if(previouslevel!=currentlevel){ //indicates new level started
previouslevel=currentlevel;
cout<<"\n";
}
cout<<currentNode->data<<" ";
if(currentNode->left)
q.push({currentNode->left,currentlevel+1});
if(currentNode->right)
q.push({currentlevel->right,currentlevel+1});
}
}
can u share the link
because in this code the symbol are not correctly visible
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.