Perfect Binary Tree Specific Level Order Traversal | Set 2 | Linked List node ; Given a perfect binary tree , print its nodes in specific level order ; for level order traversal ; Stack to print reverse ; vector to store the level ; considering size of the level ; push data of the node of a particular level to vector ; push vector containing a level in Stack ; print the Stack ; Finally pop all Nodes from Stack and prints them . ; finally print root ; Driver code
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def specific_level_order_traversal ( root ) : NEW_LINE INDENT q = [ ] NEW_LINE s = [ ] NEW_LINE q . append ( root ) NEW_LINE sz = 0 NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT v = [ ] NEW_LINE sz = len ( q ) NEW_LINE i = 0 NEW_LINE while ( i < sz ) : NEW_LINE INDENT temp = q [ 0 ] NEW_LINE q . pop ( 0 ) NEW_LINE v . append ( temp . data ) NEW_LINE if ( temp . left != None ) : NEW_LINE INDENT q . append ( temp . left ) NEW_LINE DEDENT if ( temp . right != None ) : NEW_LINE INDENT q . append ( temp . right ) NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT s . append ( v ) NEW_LINE DEDENT while ( len ( s ) > 0 ) : NEW_LINE INDENT v = s [ - 1 ] NEW_LINE s . pop ( ) NEW_LINE i = 0 NEW_LINE j = len ( v ) - 1 NEW_LINE while ( i < j ) : NEW_LINE INDENT print ( v [ i ] , " ▁ " , v [ j ] , end = " ▁ " ) NEW_LINE j = j - 1 NEW_LINE i = i + 1 NEW_LINE DEDENT DEDENT print ( root . data ) NEW_LINE DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE print ( " Specific ▁ Level ▁ Order ▁ traversal ▁ of ▁ binary ▁ tree ▁ is " ) NEW_LINE specific_level_order_traversal ( root ) NEW_LINE