Convert a Binary Tree into its Mirror Tree | Iterative Java program to convert a Binary Tree to its mirror ; 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 null 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 ; push 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
import java . util . * ; class GFG { static class Node { int data ; Node left ; Node right ; } ; static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = node . right = null ; return ( node ) ; } static void mirror ( Node root ) { if ( root == null ) return ; Queue < Node > q = new LinkedList < > ( ) ; q . add ( root ) ; while ( q . size ( ) > 0 ) { Node curr = q . peek ( ) ; q . remove ( ) ; Node temp = curr . left ; curr . left = curr . right ; curr . right = temp ; ; if ( curr . left != null ) q . add ( curr . left ) ; if ( curr . right != null ) q . add ( curr . right ) ; } } static void inOrder ( Node node ) { if ( node == null ) return ; inOrder ( node . left ) ; System . out . print ( node . data + " ▁ " ) ; inOrder ( node . right ) ; } public static void main ( String args [ ] ) { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 5 ) ; System . out . print ( " Inorder traversal of the " ▁ + " coned tree is "); inOrder ( root ) ; mirror ( root ) ; System . out . print ( " Inorder traversal of the " + ▁ " mirror tree is "); inOrder ( root ) ; } }