Skip to content

Instantly share code, notes, and snippets.

@ajinkyajawale14499
Created July 28, 2019 21:05
Show Gist options
  • Save ajinkyajawale14499/750a35fb3b86e7b63e4b330f7fd75df5 to your computer and use it in GitHub Desktop.
Save ajinkyajawale14499/750a35fb3b86e7b63e4b330f7fd75df5 to your computer and use it in GitHub Desktop.
Convert a Binary Tree into its Mirror Tree
// Convert a Binary Tree into its Mirror Tree.
//code goes here!
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
//Node Structure
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
// Utility Function
struct Node* newNode(int data)
{
struct Node* node = new Node;
node->data = data;
node->left = NULL;
node->right =NULL;
return (node);
}
// mirror function
void mirror(struct Node* node)
{
if(node == NULL)
return;
else
{
struct Node* temp;
//check subtree is leaf node or not
mirror(node->left);
mirror(node->right);
//swap the pointers in this node
temp = node->left;
node->left = node-> right;
node->right = temp;
}
}
// Helper inorder function
void inorder(struct Node* node)
{
if(node == NULL)
return;
inorder(node->left);
cout<<node->data<< " ";
inorder(node->right);
}
//Driver Function
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);
/* Print inorder traversal of the input tree */
cout << "Inorder traversal of the constructed"
<< " tree is" << endl;
inorder(root);
/* Convert tree to its mirror */
mirror(root);
/* Print inorder traversal of the mirror tree */
cout << "\nInorder traversal of the mirror tree"
<< " is \n";
inorder(root);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment