Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Hacktober #452

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions MirrorOfBinaryTree.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
// C++ program to convert a binary tree
// to its mirror
#include <bits/stdc++.h>
using namespace std;

/* A binary tree node has data, pointer
to left child and a pointer to right child */
struct Node {
int data;
struct Node* left;
struct Node* right;
};

/* Helper function that allocates a new node with
the given data and NULL left and right pointers. */
struct Node* newNode(int data)
{
struct Node* node
= (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = NULL;
node->right = NULL;

return (node);
}

/* Change a tree so that the roles of the left and
right pointers are swapped at every node.

So the tree...
4
/ \
2 5
/ \
3 1

is changed to...
4
/ \
5 2
/ \
1 3
*/
void mirror(struct Node* node)
{
if (node == NULL)
return;
else {
struct Node* temp;

/* do the subtrees */
mirror(node->left);
mirror(node->right);

/* swap the pointers in this node */
temp = node->left;
node->left = node->right;
node->right = temp;
}
}

/* Helper function to print
Inorder traversal.*/
void inOrder(struct Node* node)
{
if (node == NULL)
return;

inOrder(node->left);
cout << node->data << " ";
inOrder(node->right);
}

// Driver Code
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;
}