Level order traversal line by line | Set 3 ( Using One Queue ) | C ++ program to print levels line by line ; A Binary Tree Node ; Function to do level order traversal line by line ; Create an empty queue for level order traversal ; to store front element of queue . ; Pushing root node into the queue . ; Pushing delimiter into the queue . ; condition to check occurrence of next level . ; condition to check the occurence of next level ; pushing left child of current node . ; pushing right child of current node . ; Utility function to create a new tree node ; Driver program to test above functions ; Let us create binary tree shown above
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { struct node * left ; int data ; struct node * right ; } ; void levelOrder ( node * root ) { if ( root == NULL ) return ; queue < node * > q ; node * curr ; q . push ( root ) ; q . push ( NULL ) ; while ( q . size ( ) > 1 ) { curr = q . front ( ) ; q . pop ( ) ; if ( curr == NULL ) { q . push ( NULL ) ; cout << " STRNEWLINE " ; } else { if ( curr -> left ) q . push ( curr -> left ) ; if ( curr -> right ) q . push ( curr -> right ) ; cout << curr -> data << " ▁ " ; } } } node * newNode ( int data ) { node * temp = new node ; temp -> data = data ; temp -> left = NULL ; temp -> right = NULL ; return temp ; } int main ( ) { node * 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 ) ; levelOrder ( root ) ; return 0 ; }