Write a program to create a mirror copy of a binary tree i.e. left nodes become right and right nodes become left.
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; } }
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…….
node *mirrorImage(node *root) {
if (!root)
return NULL;
else {
node *nnode = new node(root->val);
nnode->left = mirrorImage(root->right);
nnode->right = mirrorImage(root->left);
return nnode;
}
}