This is a binary tree level order question

I am getting compilation error why

Your code is trying to access the null character, inside while loop you are popping the queue element and checking its data, right and left but it may be possible that temp is NULL, because you have checking it after popping from the queue.
So also add conditions for empty queue.

I have a condition for empty queue and I have been trying different things on this code but can’t fix it, can you tell me where the exact point of fault is, please.

1 Like

The problem which i said above is in this portion:-

            while(temp!=NULL)
            {
                node *temp = q.front();
                cout<<temp->key<< " ";
                q.pop();
                if(temp->left) q.push(temp->left);
                if(temp->right) q.push(temp->right);
            }

because here you are going to pop null elements also from the queue and then try to access that.
You can use a do while loop in your code, which will do the required thing according to your code.

These are modifications you need to do

        do
            {
                cout<<temp->key<< " ";
                q.pop();
                if(temp->left) q.push(temp->left);
                if(temp->right) q.push(temp->right);
                
                temp = q.front();
            }while(temp!=NULL);

Yes after doing the exact same thing I marked my doubt at resolved.Now I understood, but can you tell me the difference between writing node *temp = q. front and temp = q. front

@Souradeep-Kundu-824545687968212
It is done that because we can use the above created temp variable in the code which is created before the do-while loop to check it is null or not.
Because at the starting of the do-while loop you need to have a node in temp variable.