Mirror of a Binary Tree

Mirror of a binary tree

Well, one thing that always fascinates me when it comes to numbers or words is a palindrome. My blog here is a very interesting yet a simple program that would help us in finding the mirror of a binary tree and, when you place the original binary tree next to its mirrored binary tree, they would seem like a palindrome to us. Like the one in the following image.

tree2

 

 

 

For those who are quite not strong in binary trees, this post might be of good help to grasp knowledge on some major operations in binary trees.

 


#include <stdio.h>

#include<stdlib.h>
/* single node of a tree with its data, left child, right child */
struct node

{

int data;

struct node* left; //left child of a node

struct node* right; //right child of a node

};

/* new node allocation */

struct node* newnode(int data)

{

struct node* n_node=(struct node*)malloc(sizeof(struct node));

n_node->data=data;

n_node->left=NULL;

n_node->right=NULL;

return n_node;

}

/*Inorder traversal of a binary tree */

void Inorder(struct node* root)

{

if(root==NULL)

return;

Inorder(root->left);

printf("%d\t",root->data);

Inorder(root->right);

}

/* mirroring the tree with a temporary node that is used for swapping*/

void mirror(struct node* root)

{

if(root==NULL)

return;

else

{

struct node* temp=(struct node*)malloc(sizeof(struct node));

mirror(root->left);

mirror(root->right);

temp=root->left;

root->left=root->right;

root->right=temp;

}

}

void main()

{

struct node* root;

root=newnode(1);

root->left=newnode(2);

root->right=newnode(3);

root->right->left=newnode(5);

root->left->left=newnode(4);

root->right->right=newnode(6);

root->right->left->right=newnode(7);

Inorder(root);

printf("\n Mirroring the binary tree......\n");

Inorder(root);

mirror(root);

printf("|");

Inorder(root);

}

 

Have any queries, please do leave a comment.

 

 OUTPUT

 

4	2	1	5	7	3	6

 

Mirroring the binary tree……

4	2	1	5	7	3	6|6	3	7	5	1	2	4

 

Latest posts by abirami vijayakumar (see all)

Leave a Reply

Your email address will not be published. Required fields are marked *