Print nodes between two given level numbers of a binary tree | A C ++ program to print Nodes level by level berween given two levels . ; A binary tree Node has key , pointer to left and right children ; Given a binary tree , print nodes from level number ' low ' to level number ' high ' ; Marker node to indicate end of level ; Initialize level number ; Enqueue the only first level node and marker node for end of level ; Simple level order traversal loop ; Remove the front item from queue ; Check if end of level is reached ; print a new line and increment level number ; Check if marker node was last node in queue or level number is beyond the given upper limit ; Enqueue the marker for end of next level ; If this is marker , then we don 't need print it  and enqueue its children ; If level is equal to or greater than given lower level , print it ; Enqueue children of non - marker node ; Helper function that allocates a new Node with the given key and NULL left and right pointers . ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; void printLevels ( Node * root , int low , int high ) { queue < Node * > Q ; Node * marker = new Node ; int level = 1 ; Q . push ( root ) ; Q . push ( marker ) ; while ( Q . empty ( ) == false ) { Node * n = Q . front ( ) ; Q . pop ( ) ; if ( n == marker ) { cout << endl ; level ++ ; if ( Q . empty ( ) == true level > high ) break ; Q . push ( marker ) ; continue ; } if ( level >= low ) cout << n -> key << " ▁ " ; if ( n -> left != NULL ) Q . push ( n -> left ) ; if ( n -> right != NULL ) Q . push ( n -> right ) ; } } Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return ( temp ) ; } int main ( ) { struct Node * root = newNode ( 20 ) ; root -> left = newNode ( 8 ) ; root -> right = newNode ( 22 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 12 ) ; root -> left -> right -> left = newNode ( 10 ) ; root -> left -> right -> right = newNode ( 14 ) ; cout << " Level ▁ Order ▁ traversal ▁ between ▁ given ▁ two ▁ levels ▁ is " ; printLevels ( root , 2 , 3 ) ; return 0 ; }