Convert a Binary Tree into its Mirror Tree in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to convert a binary tree into its mirror tree.

For this, we will be provided with a binary tree. Our task will be to swap the values on the left and the right end creating a mirror tree from the given binary tree.


 Live Demo

using namespace std;
//binary tree node structure
struct Node{
   int data;
   struct Node* left;
   struct Node* right;
//creation of a new node with no child nodes
struct Node* newNode(int data){
   struct Node* node = (struct Node*)malloc(sizeof(struct Node));
   node->data = data;
   node->left = NULL;
   node->right = NULL;
void mirror(struct Node* node){
   if (node == NULL)
      struct Node* temp;
      //swapping the subtrees
      temp = node->left;
      node->left = node->right;
      node->right = temp;
//printing the inorder traversal
void print_tree(struct Node* node){
   if (node == NULL)
   cout << node->data << " ";
int main(){
   struct Node *root = newNode(1);
   root->left = newNode(2);
   root->right = newNode(3);
   root->left->left = newNode(4);
   root->left->right = newNode(5);
   //printing the initial tree
   cout << "Inorder traversal of the constructed" << endl;
   //printing the mirror tree
   cout << "\nInorder traversal of the mirror tree" << endl;
   return 0;


Inorder traversal of the constructed
4 2 5 1 3
Inorder traversal of the mirror tree
3 1 5 2 4
Published on 02-Jan-2020 10:13:48