Print level order traversal line by line in C++ Programming.

Given the binary tree, the function must find out the level order traversal of a tree line by line.

Level order traversal: Left Root Right, which means firstly print left child of a node than the value of a root and then go to the right child but here we have to do line by line which will start from left and will end at the right node of a given binary tree.

The binary tree given above will generate the following output −

Level 0: 3
Level 1: 2 1
Level 2: 10 20 30


Step 1 -> create a structure of a node as
   struct node
      struct node *left, *right
      int data
Step 2 -> function to create a node
   node* newnode(int data)
   node *temp = new node
   temp->data = data
   temp->left = temp->right= NULL
   return temp
step 3 -> function for inorder traversal
   void levelorder(node *root)
   IF root = NULL
   queue<node *> que
   Loop While que.empty() = false
      int count = que.size()
      Loop While count > 0
         node *node = que.front()
         print node->data
      IF node->left != NULL
      IF node->right != NULL
      Decrement count by 1
Step 4 -> In main() function
   Create tree using node *root = newnode(3)
   Call levelorder(root)


 Live Demo

#include <iostream>
#include <queue>
using namespace std;
//it will create a node structure
struct node{
   struct node *left;
   int data;
   struct node *right;
void levelorder(node *root){
   if (root == NULL)
   queue<node *> que;
   while (que.empty() == false){
      int count = que.size();
      while (count > 0){
         node *node = que.front();
         cout << node->data << " ";
         if (node->left != NULL)
         if (node->right != NULL)
//it will create a new node
node* newnode(int data){
   node *temp = new node;
   temp->data = data;
   temp->left = NULL;
   temp->right = NULL;
   return temp;
int main(){
   // it will generate the binary tree
   node *root = newnode(3);
   root->left = newnode(2);
   root->right = newnode(1);
   root->left->left = newnode(10);
   root->left->right = newnode(20);
   root->right->right = newnode(30);
   return 0;


if we run the above program then it will generate the following output

3 2 1 10 20 30