Thursday, April 3, 2014

PROGRAM TO CONVERT GIVEN BINARY TREE TO DOUBLE LINKED LIST


#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *left,*right;
};
struct node  *array[];
int x=-1;
int size;
void insertTree(struct node **root,int data){
if(!(*root)){
*root=malloc(sizeof(struct node));
(*root)->data=data;
(*root)->left=NULL;
(*root)->right=NULL;
}
else {
if(data<(*root)->data)
insertTree(&((*root)->left),data);
else
insertTree(&((*root)->right),data);
}
}
void inoder(struct node *root){
if(root){
inoder(root->left);
array[++x]=root;
inoder(root->right);
}
}
void linekdlist(){
int i;
for(i=0;i<size;i++){
if(i==0){
array[i]->left=NULL;
array[i]->right=array[i+1];
}
else{
if(i==size-1)
{
array[i]->right=NULL;
array[i]->left=array[i-1];
}
else{
array[i]->left=array[i-1];
array[i]->right=array[i+1];
}
}
}}
void display(struct node *root){
while(root){
printf("data=%d\n",root->data);
root=root->right;
}
}
int main(){
struct node *root=NULL;
int i,temp;
printf("\nenter the total number of data:");
scanf("%d",&size);
for(i=0;i<size;i++){
printf("\nenter the data: ");
scanf("%d",&temp);
insertTree(&root,temp);
}
inoder(root);
linekdlist();
root=array[0];
printf("Linked list:\n");
display(root);
for(i=0;i<size;i++)
free(array[i]);
return 0;
}