I want to store the binary tree in the array with null values at the missing nodes.
For eg:
Input:
1
/ \
2 3
/ \ \
4 5 6
Output:{1,2,3,4,5,0,6}
I have tried linear traversal of the binary tree in the array, but I want null in the missing nodes positions of the tree.
std::vector< int > levelorder( tree *root){
queue<tree*> q;
tree* temp;
q.push(root);
while(!q.empty()){
temp=q.front();
q.pop();
arr.push_back(temp->data);
if(temp->left && temp->right)
{
q.push(temp->left);
q.push(temp->right);
}
else if(temp->left && !temp->right)
{
q.push(temp->left);
arr.insert(0);
}
else if(temp->right && !temp->left)
{
q.push(temp->right);
arr.push_back(0);
}
}
return arr;
}
int main()
{
tree *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->right = newNode(6);
cout<<"Level Order traversal of binary tree is :"<<endl;
levelorder(root);
for(int i =0; i<arr.size(); i++)
{
cout<< arr[i]<<" ";
}
return 0;
}
I am getting output:{1,2,3,0,4,5,6} But I want the output as: {1,2,3,4,5,0,6}