Flip Binary Tree | Python3 program to flip a binary tree ; A binary tree node structure ; method to flip the binary tree ; Initialization of pointers ; Iterate through all left nodes ; Swapping nodes now , need temp to keep the previous right child Making prev ' s ▁ right ▁ as ▁ curr ' s left child ; Storing curr 's right child ; Making prev as curr 's right  child ; Iterative method to do 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
from collections import deque 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 flipBinaryTree ( root ) : NEW_LINE INDENT curr = root NEW_LINE next = None NEW_LINE temp = None NEW_LINE prev = None NEW_LINE while ( curr ) : NEW_LINE INDENT next = curr . left NEW_LINE curr . left = temp NEW_LINE temp = curr . right NEW_LINE curr . right = prev NEW_LINE prev = curr NEW_LINE curr = next NEW_LINE DEDENT return prev NEW_LINE DEDENT def printLevelOrder ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT q = deque ( ) NEW_LINE q . append ( root ) 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 . popleft ( ) NEW_LINE print ( node . data , end = " ▁ " ) 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 print ( ) NEW_LINE 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 . 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 ( " Level order traversal of the flipped " ▁ " tree " ) NEW_LINE printLevelOrder ( root ) NEW_LINE DEDENT