Given a binary tree, write an algorithm to find its mirror image with minimal time and space complexities.

Note: If you know the answer and if you feel it is simple also please post the answers so that others will come to know about the answers.

This question was sent by my friend through mail.

Solutions Suggested



Sol 1
CODE
void PrintMirror(node *root)
{

    if(node!=NULL)
       PrintMirror(root->right);
    Printf(root->data);
    PrintMirror(root->left);
    
}

In case of implementation using array 2i+1 stores left child of ith node and 2i+2 stores right element.
CODE
for(int i=0;i<(2^levels)-1;i++)
{
   swap(tree[2i+1],tree[2i+2]);
}

Note: Null nodes are also to be swaped hence (2^levels)-1 -- Suggested by my friend...



Sol 2
Another Solution....
CODE
void Mirror(node *ptr)
{
     if(ptr!=(node *) NULL)
     {
          node* right=ptr->right;
          Mirror(ptr->left);
          Mirror(ptr->right);
          ptr->right=ptr->left;
          ptr->left=right;
     }
}

Time complexity : O(n). Each node is processed once.
Space complexity : only one temp ptr used.

More solutions welcome...

Notice from rvalkass:

Double post merged. Remember the edit button is available for you to use. Also, any code needs to be in CODE tags.




One more Solution here...
Sol 3
One more algo
CODE
node* mirror(node **tree)
{
  node * temptree;
  if(*tree!=(node*)NULL)
  {
      temptree =(node*)malloc(sizeof(node));
      temptree->left   = mirror(tree->right);
      temptree->data = tree->data;
      temptree->right = mirror(tree->left);
      return(temptree);
  }
   else
    printf("Tree is empty !!");

 

 

 


Reply