Suppose there is a tree:
1
/ \\
2 3
/ \\
4 5
Then the mirror image will
Recursive Java Code
public class TreeMirrorImageCreator {
public static Node createMirrorImage(Node originalNode,Node mirroredNode){
mirroredNode.setValue(originalNode.getValue());
if(originalNode.getLeft() != null){
mirroredNode.setLeft(createMirrorImage(originalNode.getRight(),new Node(0)));
}
if(originalNode.getRight() != null){
mirroredNode.setRight(createMirrorImage(originalNode.getLeft(), new Node(0)));
}
return mirroredNode;
}
}
void mirror(struct node* node)
{
if (node==NULL)
{
return;
}
else
{
struct node* temp;
mirror(node->left);
mirror(node->right);
temp = node->left;
node->left = node->right;
node->right = temp;
}
}
void mirror(node<t> *& root2,node<t> * root)
{
if(root==NULL)
{
root2=NULL;
}
else {
root2=new node<t>;
root2->data=root->data;
root2->left=NULL;
root2->right=NULL;
mirror(root2->left,root->right);
mirror(root2->right,root->left);
}
}
Sounds like homework.
It looks very easy. Write a recursive routine that depth-first visits every node and builds the mirror tree with left and right reversed.
struct node *mirror(struct node *here) {
if (here == NULL)
return NULL;
else {
struct node *newNode = malloc (sizeof(struct node));
newNode->value = here->value;
newNode->left = mirror(here->right);
newNode->right = mirror(here->left);
return newNode;
}
}
This returns a new tree - some other answers do this in place. Depends on what your assignment asked you to do :)
Banal solution:
for each node in tree
exchange leftchild with rightchild.
Recursive and Iterative methods in JAVA: 1) Recursive:
public static TreeNode mirrorBinaryTree(TreeNode root){
if(root == null || (root.left == null && root.right == null))
return root;
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
mirrorBinaryTree(root.left);
mirrorBinaryTree(root.right);
return root;
}
2) Iterative:
public static TreeNode mirrorBinaryTreeIterative(TreeNode root){
if(root == null || (root.left == null && root.right == null))
return root;
TreeNode parent = root;
Stack<TreeNode> treeStack = new Stack<TreeNode>();
treeStack.push(root);
while(!treeStack.empty()){
parent = treeStack.pop();
TreeNode temp = parent.right;
parent.right = parent.left;
parent.left = temp;
if(parent.right != null)
treeStack.push(parent.right);
if(parent.left != null)
treeStack.push(parent.left);
}
return root;
}