fork(2) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. class Node {
  8. public Node left;
  9. public int data;
  10. public Node right;
  11.  
  12. public Node(int val) {
  13. this.data=val;
  14. }
  15. }
  16.  
  17.  
  18. /* Name of the class has to be "Main" only if the class is public. */
  19. class MirrorTree {
  20.  
  21. public void mirror(Node root) {
  22. if(root== null)
  23. return ;
  24. else
  25. {
  26. mirror(root.left);
  27. mirror(root.right);
  28.  
  29. swap(root);
  30. }
  31. }
  32.  
  33. // Swap Sub Trees of a Node
  34. private void swap(Node node) {
  35. Node temp=node.right;
  36. node.right=node.left;
  37. node.left=temp;
  38.  
  39. }
  40.  
  41. // inorder display subroutine
  42. public void inorder(Node r) {
  43. if (r != null) {
  44. inorder(r.left);
  45. System.out.print(r.data + "\t");
  46. inorder(r.right);
  47. }
  48. }
  49.  
  50. public static void main(String[] args) {
  51. Node root=new Node(12);
  52.  
  53. Node n1=new Node(14);
  54. Node n2=new Node(18);
  55. Node n3=new Node(10);
  56. root.left=new Node(8);
  57. root.right=new Node(16);
  58. root.left.left=new Node(6);
  59. root.left.right=n3;
  60. root.right.left=n1;
  61. root.right.right=n2;
  62.  
  63.  
  64. MirrorTree m=new MirrorTree();
  65. System.out.println("Before:");
  66. m.inorder(root);
  67. m.mirror(root);
  68.  
  69. System.out.println("\n After:");
  70. m.inorder(root);
  71.  
  72. }
  73. }
Success #stdin #stdout 0.08s 380160KB
stdin
Standard input is empty
stdout
Before:
6	8	10	12	14	16	18	
 After:
18	16	14	12	10	8	6