Level order traversal line by line | Set 3 ( Using One Queue ) | Python3 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 ; Pushing root node into the queue . ; Pushing delimiter into the queue . ; Condition to check occurrence of next level . ; Pushing left child of current node . ; Pushing left child current node ; Pushing right child of current node . ; Driver code ; Let us create binary tree shown above
from collections import deque as queue NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def levelOrder ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT q = queue ( ) NEW_LINE q . append ( root ) NEW_LINE q . append ( None ) NEW_LINE while ( len ( q ) > 1 ) : NEW_LINE INDENT curr = q . popleft ( ) NEW_LINE if ( curr == None ) : NEW_LINE q . append ( None ) NEW_LINE print ( ) NEW_LINE else : NEW_LINE INDENT if ( curr . left ) : NEW_LINE INDENT q . append ( curr . left ) NEW_LINE DEDENT if ( curr . right ) : NEW_LINE INDENT q . append ( curr . right ) NEW_LINE DEDENT print ( curr . data , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . right . right = Node ( 6 ) NEW_LINE levelOrder ( root ) NEW_LINE DEDENT