MCN Professionals | Interview Question of the day
MCN Professionals is starting Industrial Training for MCA-2012 Batch. Have a look at our Industrial Training Program and Course Details.
-----------------------------------------------------------------------------------------------------------------------------------------
Today's Question:
Given a Binary Tree, write a function which will convert that tree to its Mirror Tree. For Example: If the Binary Tree is
1
/ \
2 3
/ \
4 5
Then the Mirror is
Solution:
As I have written in my earlier posts also, Tree problems are better solved using
recursion(But recursion comes with its side effect). Finding the Mirror can also be visualized recursively.
Algorithm:
- Compute Mirror of Left Sub-Tree
- Compute Mirror of Right Sub-Tree
- swap the left and right subtree values
Code:
void mirrorTree(Node* root)
{
if (!root)
return;
mirrorTree(root->lptr);
mirrorTree(root->rptr);
// swap the left & right pointers
Node* temp = root->lptr;
root->lptr = root->rptr;
root->rptr = temp;
}
---------------------------------------------------------------------------
Interview Questions Archive:
To see all the questions in the category click
here...