Tuesday, February 18, 2014

Create a mirror of a binary tree


http://www.geeksforgeeks.org/write-an-efficient-c-function-to-convert-a-tree-into-its-mirror-tree/
http://geekyjumps.blogspot.in/2013/09/create-mirror-of-binary-tree.html


Algorithm - Mirror(tree):

(1)  Call Mirror for left-subtree i.e., Mirror(left-subtree)
(2)  Call Mirror for right-subtree i.e., Mirror(left-subtree)
(3)  Swap left and right subtrees.
          temp = left-subtree
          left-subtree = right-subtree
          right-subtree = temp


Program- Mirror(tree):

 public static void mirrorTree(Node root){
  if(root == null) return;
  
  Node tmp = root.left;
  root.left = root.right;
  root.right = tmp;
  
  mirrorTree(root.left);
  mirrorTree(root.right);
 }




static Node mirrorBT(Node root)
{

//Base conditions
if(root == null) return null;

if(root.left == null && root.right == null) return root;

if(root.left == null)
{
root.left = root.right;
root.right = null;
return root;
}

if(root.right == null)
{
root.right = root.left;
root.left = null;
return root;
}
//

Node leftTree = mirrorBT(root.left);
Node rightTree = mirrorBT(root.right);

// swap the child nodes of root
root.left = rightTree;
root.right = leftTree;

return root;

  }

No comments:

Post a Comment