Convert a Binary Tree into its Mirror Tree | A binary tree node has data , pointer to left child and a pointer to right child Helper function that allocates a new node with the given data and None left and right pointers ; Change a tree so that the roles of the left and right pointers are swapped at every node . So the tree ... 4 / \ 2 5 / \ 1 3 is changed to ... 4 / \ 5 2 / \ 3 1 ; Do BFS . While doing BFS , keep swapping left and right children ; pop top node from queue ; swap left child with right child ; append left and right children ; Helper function to print Inorder traversal . ; Driver code ; Print inorder traversal of the input tree ; Convert tree to its mirror ; Print inorder traversal of the mirror tree
class newNode : 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 mirror ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( root ) NEW_LINE while ( len ( q ) ) : NEW_LINE INDENT curr = q [ 0 ] NEW_LINE q . pop ( 0 ) NEW_LINE curr . left , curr . right = curr . right , curr . left NEW_LINE 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 DEDENT DEDENT def inOrder ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT inOrder ( node . left ) NEW_LINE print ( node . data , end = " ▁ " ) NEW_LINE inOrder ( node . right ) NEW_LINE DEDENT 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 print ( " Inorder ▁ traversal ▁ of ▁ the ▁ constructed ▁ tree ▁ is " ) NEW_LINE inOrder ( root ) NEW_LINE mirror ( root ) NEW_LINE print ( " Inorder traversal of the mirror tree is " ) NEW_LINE inOrder ( root ) NEW_LINE