In this article, we will implement the algorithm to find the mirror image of a given binary tree in Java. A mirror image of a binary tree is another binary tree with left and right children of all non-leaf nodes of the given binary tree are interchanged.
Below is the image that shows the mirror image of a given binary tree.
We will be using a recursive approach to find the mirror image of a given binary tree.
Binary Tree Node Implementation
Below is the Binary tree node class implementattion in Java.
public class BinaryTreeNode { private int data; private BinaryTreeNode leftNode; private BinaryTreeNode rightNode; public BinaryTreeNode(int data){ this.data = data; } //setters and getters
Algorithm Implementation
The left child of any node in the given tree will be the right child of the node in the mirrroe image. Below is the implementation for the same. The InOrdeer traversal is just to validate the mirrored binary tree.
public class BinaryTreeMirror { public static BinaryTreeNode mirrorBinaryTree(BinaryTreeNode root){ if (root == null){ return null; } BinaryTreeNode left = mirrorBinaryTree(root.getLeftNode()); BinaryTreeNode right = mirrorBinaryTree(root.getRightNode()); root.setRightNode(left); root.setLeftNode(right); return root; } } public static void inOrder(BinaryTreeNode root){ if (root != null){ inOrder(root.getLeftNode()); System.out.print(root.getData() + " "); inOrder(root.getRightNode()); } }
Below is our main function for running our implementation.
public static void main(String[] args) { BinaryTreeNode root = new BinaryTreeNode(15); root.setLeftNode(new BinaryTreeNode(7)); root.getLeftNode().setLeftNode(new BinaryTreeNode(5)); root.getLeftNode().setRightNode(new BinaryTreeNode(10)); root.getLeftNode().getRightNode().setLeftNode(new BinaryTreeNode(8)); root.setRightNode(new BinaryTreeNode(30)); root.getRightNode().setLeftNode(new BinaryTreeNode(25)); root.getRightNode().setRightNode(new BinaryTreeNode(35)); inOrder(root); System.out.println(); BinaryTreeMirror.mirrorBinaryTree(root); inOrder(root); }Output
5 7 8 10 15 25 30 35 35 30 25 15 10 8 7 5
Conclusion
In this article, we implemented the algorithm to find the mirror image of a given binary tree in Java.