Can any TA please share the code to build a binary tree from the given level order input
1 2 3 4 5 -1 6 -1 -1 -1 -1 -1 -1
Can any TA please share the code to build a binary tree from the given level order input
1 2 3 4 5 -1 6 -1 -1 -1 -1 -1 -1
You can maintain a queue of nodes, push the root node inside the queue, then pop the node, but before popping, you need to push its children to the queue… You can follow the approach as :
node *buildtree() //build tree function to build tree level wise
{
int d;
cin>>d;
queue<node *>q;
node root=new node(d);
q.push(root);
int c1,c2;
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;
}