Mirror image of a binary tree

Write a program to create a mirror copy of a binary tree i.e. left nodes become right and right nodes become left.

mirrorImage

Solution 1 : Following program will create a new mirror tree.

struct node
{
    int value;
    struct node* left;
    struct node* right;
};


struct node *mirrorTree(struct node *root)
{
  struct node *temp;
  
  if(root==NULL)
    return(NULL);
   
  temp = (struct node *) malloc(sizeof(struct node));
  temp->value = root->value;

  temp->left  = mirrorTree(root->right);
  temp->right = mirrorTree(root->left);

  return(temp);
}

Solution 2: This program will convert tree into it’s mirror tree.

void tree_mirror(struct node* node) 
{ 
   struct node *temp;

   if (node==NULL) 
   { 
     return; 
   } 
   else 
   { 
      tree_mirror(node->left); 
      tree_mirror(node->right); 

      // Swap the pointers in this node 
      temp = node->left; 
      node->left = node->right; 
      node->right = temp; 
   } 
}

One Thought on “Mirror image of a binary tree

  1. Satveer Singh on May 29, 2014 at 5:09 pm said:

    i think we cannot do clone and mirror two operation together so approach 1 will fail….
    Did u check it what is output….we should do first clone then once it get done called mirror function…….

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation