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 iteratively.


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

/*
Write a Function to Convert a given Binary Tree into its Mirror Tree iteratively.
(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 MirrorOfBinaryTreeInIterativeWay {
 private Node rootNode;

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

 public MirrorOfBinaryTreeInIterativeWay(){
  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 = createMirrorIteratively(rootNode);
  System.out.println();
  printTreeLevelOrder(mirrorRoot);
 }

 private Node createMirrorIteratively(Node rootNode) {
  if(rootNode==null){
   return null;
  }
  Queue<Node> q = new LinkedList<Node>();
  q.add(rootNode);
  while(!q.isEmpty()){
   Node temp = q.poll();
   Node swapTemp = temp.getLeft();
   temp.setLeft(temp.getRight());
   temp.setRight(swapTemp);
   if(temp.getLeft()!=null){
    q.add(temp.getLeft());
   }
   if(temp.getRight()!=null){
    q.add(temp.getRight());
   }
  }
  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);
   }
  }
 }
}