Print the nodes at odd levels of a tree | Iterative Python3 program to prodd level nodes A Binary Tree Node Utility function to create a new tree Node ; Iterative method to do level order traversal line by line ; Base Case ; Create an empty queue for level order traversal ; Enqueue root and initialize level as odd ; nodeCount ( queue size ) indicates number of nodes at current level . ; Dequeue all nodes of current level and Enqueue all nodes of next level ; Driver Code
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def printOddNodes ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( root ) NEW_LINE isOdd = True NEW_LINE while ( 1 ) : NEW_LINE INDENT nodeCount = len ( q ) NEW_LINE if ( nodeCount == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT while ( nodeCount > 0 ) : NEW_LINE INDENT node = q [ 0 ] NEW_LINE if ( isOdd ) : NEW_LINE INDENT print ( node . data , end = " ▁ " ) NEW_LINE DEDENT q . pop ( 0 ) NEW_LINE if ( node . left != None ) : NEW_LINE INDENT q . append ( node . left ) NEW_LINE DEDENT if ( node . right != None ) : NEW_LINE INDENT q . append ( node . right ) NEW_LINE DEDENT nodeCount -= 1 NEW_LINE DEDENT isOdd = not isOdd NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE printOddNodes ( root ) NEW_LINE DEDENT