Created
July 28, 2019 21:20
-
-
Save ajinkyajawale14499/98d9d8117ddea61a4d9dd7ee7d60e442 to your computer and use it in GitHub Desktop.
Convert a Binary Tree into its Mirror Tree
This file contains hidden or 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.
Learn more about bidirectional Unicode characters
class Node{ | |
int data; | |
Node left; | |
Node right; | |
public Node(int data){ | |
this.data = data; | |
this.left = null; | |
this.right =null; | |
} | |
} | |
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(1); | |
root.left = new Node(2); | |
root.right = new Node(3); | |
root.left.left = new Node(4); | |
root.left.right = new Node(5); | |
// root.right.left = new Node(5); | |
// root.right.right = new Node(7); | |
MirrorTree i = new MirrorTree(); | |
i.mirror(root); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment