Last active
April 22, 2017 12:48
-
-
Save roychowdhuryrohit-dev/b87c05fe3e82ba087f059d12a9140159 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* ----ROHIT ROY CHOWDHURY(Zeu5)---- | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
typedef struct S | |
{ | |
int data; | |
struct S *l,*r; | |
} node; | |
void insert(node **str,int item) | |
{ | |
node *ptr = (node *)malloc(sizeof(node )),*temp; | |
ptr->data=item; | |
ptr->l=ptr->r=NULL; | |
if(*str==NULL) | |
{ | |
*str=ptr; | |
return; | |
} | |
temp=*str; | |
while(1) | |
{ | |
if(item<temp->data) | |
{ | |
if(temp->l==NULL) | |
{ | |
temp->l=ptr; | |
return; | |
} | |
temp=temp->l; | |
} | |
else | |
{ | |
if(temp->r==NULL) | |
{ | |
temp->r=ptr; | |
return; | |
} | |
temp=temp->r; | |
} | |
} | |
} | |
void mirror(node **p,int l)//Will work with any binary tree. | |
{ | |
int i,j=0,l1,f=1; | |
l1=2*l; | |
node **p1=(node **)malloc(sizeof(node *)*l);//Aux. array | |
node **a=(node **)malloc(sizeof(node *)*l1);//Array for storing next level | |
for(i=0;i<l;i++) | |
p1[i]=p[l-i-1];//to reverse the array | |
for(i=0;i<l;i++) | |
{ | |
if(p1[i]!=NULL) | |
{ | |
a[j++]=p1[i]->r; | |
a[j++]=p1[i]->l; | |
if(p1[i]->l!=NULL || p1[i]->r!=NULL)//To detect intermediate levels | |
f=0; | |
} | |
} | |
j=0; | |
p=p1; | |
for(i=0;i<l;i++) | |
{ | |
if(p[i]!=NULL) | |
{ | |
p[i]->l=a[j++]; | |
p[i]->r=a[j++]; | |
} | |
} | |
if(f)//Stop on reaching last level | |
return; | |
else | |
mirror(a,l1); | |
} | |
void traverse(node *p)//Level-wise traversal | |
{ | |
int f=-1,r=-1,i; | |
node *q[20],*x; | |
q[++r]=p; | |
while(f!=r) | |
{ | |
x=q[++f]; | |
if(x!=NULL) | |
{ | |
if(x->l!=NULL) | |
{ | |
q[++r]=x->l; | |
} | |
if(x->r!=NULL) | |
{ | |
q[++r]=x->r; | |
} | |
printf("%d, ",x->data); | |
} | |
} | |
puts(""); | |
} | |
main() | |
{ | |
node *s,*s1;int n,f=1; | |
s=NULL; | |
s1=NULL; | |
while(f) | |
{ | |
puts("1.Insert.\n2.Print original tree.\n3.Exit"); | |
scanf("%d",&n); | |
switch(n) | |
{ | |
case 1: | |
printf("Enter item - "); | |
scanf("%d",&n); | |
insert(&s,n); | |
insert(&s1,n); | |
break; | |
case 2: | |
traverse(s); | |
break; | |
case 3: | |
f=0; | |
} | |
} | |
mirror(&s1,1); | |
puts("Original tree -"); | |
traverse(s); | |
puts("Mirror -"); | |
traverse(s1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Program to create mirror image of a binary tree.