Print nodes between two given level numbers of a binary tree | A binary tree node ; Given a binary tree , print nodes form 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 ; print Q Simple level order traversal loop ; Remove the front item from queue ; print Q 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 nubmer 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 ; Driver program to test the above function
class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def printLevels ( root , low , high ) : NEW_LINE INDENT Q = [ ] NEW_LINE marker = Node ( 11114 ) NEW_LINE level = 1 NEW_LINE Q . append ( root ) NEW_LINE Q . append ( marker ) NEW_LINE while ( len ( Q ) > 0 ) : NEW_LINE INDENT n = Q [ 0 ] NEW_LINE Q . pop ( 0 ) NEW_LINE if n == marker : NEW_LINE INDENT print NEW_LINE level += 1 NEW_LINE if len ( Q ) == 0 or level > high : NEW_LINE INDENT break NEW_LINE DEDENT Q . append ( marker ) NEW_LINE continue NEW_LINE DEDENT if level >= low : NEW_LINE INDENT print n . key , NEW_LINE DEDENT if n . left is not None : NEW_LINE INDENT Q . append ( n . left ) NEW_LINE Q . append ( n . right ) NEW_LINE DEDENT DEDENT DEDENT root = Node ( 20 ) NEW_LINE root . left = Node ( 8 ) NEW_LINE root . right = Node ( 22 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 12 ) NEW_LINE root . left . right . left = Node ( 10 ) NEW_LINE root . left . right . right = Node ( 14 ) NEW_LINE print " Level ▁ Order ▁ Traversal ▁ between ▁ given ▁ two ▁ levels ▁ is " , NEW_LINE printLevels ( root , 2 , 3 ) NEW_LINE