Flip Binary Tree | A binary tree node ; method to flip the binary tree ; Recursively call the same method ; Rearranging main root Node after returning from recursive call ; Iterative method to do the level order traversal line by line ; Base Case ; Create an empty queue for level order traversal ; Enqueue root and initialize height ; 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 Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . right = None NEW_LINE self . left = None NEW_LINE DEDENT DEDENT def flipBinaryTree ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return root NEW_LINE DEDENT if ( root . left is None and root . right is None ) : NEW_LINE INDENT return root NEW_LINE DEDENT flippedRoot = flipBinaryTree ( root . left ) NEW_LINE root . left . left = root . right NEW_LINE root . left . right = root NEW_LINE root . left = root . right = None NEW_LINE return flippedRoot NEW_LINE DEDENT def printLevelOrder ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT from Queue import Queue NEW_LINE q = Queue ( ) NEW_LINE q . put ( root ) NEW_LINE while ( True ) : NEW_LINE INDENT nodeCount = q . qsize ( ) NEW_LINE if nodeCount == 0 : NEW_LINE INDENT break NEW_LINE DEDENT while nodeCount > 0 : NEW_LINE INDENT node = q . get ( ) NEW_LINE print node . data , NEW_LINE if node . left is not None : NEW_LINE INDENT q . put ( node . left ) NEW_LINE DEDENT if node . right is not None : NEW_LINE INDENT q . put ( node . right ) NEW_LINE DEDENT nodeCount -= 1 NEW_LINE DEDENT print NEW_LINE DEDENT DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . right . left = Node ( 4 ) NEW_LINE root . right . right = Node ( 5 ) NEW_LINE print " Level ▁ order ▁ traversal ▁ of ▁ given ▁ tree " NEW_LINE printLevelOrder ( root ) NEW_LINE root = flipBinaryTree ( root ) NEW_LINE print   " NEW_LINE Level order traversal of the flipped tree " NEW_LINE printLevelOrder ( root ) NEW_LINE