Given Tree
a
/ \
b c
/ \
d e
Mirror Tree
a
/ \
c b
/ \
e d
ALGO
Here we have simply traversed the tree in postfix manner and instead of printing the node we have switched it right child with left and vice versa
Per-order is used because root's child will be switched at last
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<time.h>//for producing random tree
struct node
{int n;
struct node *left;
struct node *right;
};
int c=0;
create(int d,struct node**m)
{
struct node *q=*m;
if(*m==NULL)
{
struct node *r=(struct node*)malloc(sizeof(struct node));
r->n=d;
r->left=NULL;
r->right=NULL;
*m=r;
}
else
{
if(q->n>d)
create(d,&(q->left));
if(q->n<d)
create(d,&(q->right));
}
}
display(struct node *root)
{
if(root==NULL)
return;
else
{
display(root->left);
display(root->right);
printf("%d\n",(root->n));
}
}
conversion(struct node *m)//code for creating mirror tree of the given tree
{
struct node *n=m;
if(n==NULL)
return;
conversion(n->left);
conversion(n->right);
struct node *t=n->left;
n->left=n->right;
n->right=t;
}
main()
{
struct node *root=NULL;
srand(time(NULL));
int i;
for(i=0;i<=5;i++)
create((rand()%20),&root);
display(root);//before conversion
conversion(root);
display(root);//after conversion
getch();
}
No comments:
Post a Comment