Build a binary tree from given levelorder : 1 2 3 4 5 6 -1 -1 -1 -1 -1 -1 -1

Hello,

I am not able to build a binary tree from given level order. Can you please help.

Here, you are required to take a queue of nodes as ,
queue<node *>q;
Take the input data from the user, which will be the root node and push it into the queue…as :
q.push(root);
then take two values, c1 and c2 which represents the left and right children of the root node,
and while queue is not empty, you will take the front element, pop it and then input its two children c1 and c2 if c1 and c2 are not equal to 1, if they arent equal to -1, push them into the queue, and when they will become parent node, when u pop them, store their children in the queue…

while(!q.empty())
{
node *f=q.front();
q.pop();
cin>>c1>>c2;
if(c1!=-1)
{
f->left=new node(c1);
q.push(f->left);
}
if(c2!=-1)
{
f->right=new node(c2);
q.push(f->right);
}
}
return root;
}

This is the basic approach you will follow, You can also go through online video lecture of Binary tree BFS traversal -1 and 2 method of tree, which works on the similar logic… You can go through it once for better understanding…