This blog will soon be merged with

JavaByPatel

which explains each solution in detail, to visit new blog, click JavaByPatel

Friday, 26 June 2015

Given a Binary Tree or a Binary Search Tree, Convert it into its Mirror Tree recursively.


package tree;
import java.util.LinkedList;
import java.util.Queue;

/*
 Write a Function to Convert a given Binary Tree into its Mirror Tree recursively.
 (Mirror Tree: Mirror Tree of a binary tree is where left and right child of every node of given binary tree is interexchange.)

       Input:                     output:

                  50                          50           
                 /  \                        /  \
                /    \                      /    \
              20      80                  80      20
             /  \    /  \                /  \    /  \
            10  30  70  100            100  70  30  10

 */
public class MirrorOfBinaryTreeWithRecursion {
 private Node rootNode;

 public static void main(String[] args) {
  new MirrorOfBinaryTreeWithRecursion();
 }

 public MirrorOfBinaryTreeWithRecursion(){
  addNode(rootNode, 50); 
  addNode(rootNode, 20); 
  addNode(rootNode, 80); 
  addNode(rootNode, 10); 
  addNode(rootNode, 30);
  addNode(rootNode, 70);
  addNode(rootNode, 100);

  printTreeLevelOrder(rootNode);
  Node mirrorRoot = createMirror(rootNode);
  System.out.println();
  printTreeLevelOrder(mirrorRoot);
 }
  
 private Node createMirror(Node rootNode) {
  if(rootNode==null){
   return null;
  }
  
  Node left = createMirror(rootNode.getLeft());
  Node right = createMirror(rootNode.getRight());
  
  rootNode.setRight(left);
  rootNode.setLeft(right);
  
  return rootNode;
 }

 private void printTreeLevelOrder(Node rootNode){
  if(rootNode==null)
   return;
  Queue<Node> queue = new LinkedList<Node>();
  queue.add(rootNode);

  while(!queue.isEmpty()){
   Node obj = (Node)queue.poll();
   System.out.print(obj.getData() + " ");
   if(obj.getLeft()!=null)
    queue.add(obj.getLeft());

   if(obj.getRight()!=null)
    queue.add(obj.getRight());
  }
 } 

 private void addNode(Node rootNode, int data){
  if(rootNode==null){
   Node temp1 = new Node(data);
   this.rootNode=temp1;
  }else{
   addNodeInProperPlace(rootNode, data);
  }
 }
 
 private void addNodeInProperPlace(Node rootNode, int data){ 
  if(data>rootNode.getData()){
   if(rootNode.getRight()!=null){
    addNode(rootNode.getRight(), data);
   }else{
    Node temp1 = new Node(data);
    rootNode.setRight(temp1);
   }
  }else if(data<rootNode.getData()){
   if(rootNode.getLeft()!=null){
    addNode(rootNode.getLeft(), data);
   }else{
    Node temp1 = new Node(data);
    rootNode.setLeft(temp1);
   }
  }
 }
}