# Given a binary tree, Convert it into its Mirror Tree

Objective: Given a binary tree, Convert it into its Mirror Tree

Mirror Tree: Mirror Tree of a binary tree is where left and right child of every node of given binary tree is interexchanged.

Input: A binary tree.

Example:

Approach:

• Do the PreOrder Traversal.
• Starting from the root, swap the left and right childs.
• Recursively call the same procedure in the leftsubtree and right subtree.

Complete Code:

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.

 public class MirrorTree { public void mirror(Node root){ print(root); Node x = mirrorTree(root); System.out.print("\n Mirror Image "); print(x); } public Node mirrorTree(Node root){ if(root!=null){ Node t = root.left; root.left = root.right; root.right = t; mirrorTree(root.right); mirrorTree(root.left); } return root; } public void print(Node root){ if(root!=null){ print(root.left); System.out.print("" + root.data); print(root.right); } } public static void main (String[] args) throws java.lang.Exception { Node root = new Node(4); root.left = new Node(2); root.right = new Node(6); root.left.left = new Node(1); root.left.right = new Node(3); root.right.left = new Node(5); root.right.right = new Node(7); MirrorTree i = new MirrorTree(); i.mirror(root); } } class Node{ int data; Node left; Node right; public Node(int data){ this.data = data; this.left = null; this.right =null; } }

view raw

MirrorTree.java

hosted with ❤ by GitHub

Output:

```1 2 3 4 5 6 7
Mirror Image  7 6 5 4 3 2 1
```

### 1 thought on “Given a binary tree, Convert it into its Mirror Tree”

1. Nice article. Thanks