program to generate a binary tree in C.

#include<stdio.h>
int x;
struct nodetype
{
int info;
struct nodetype *left,*right;
};
typedef struct nodetype *nodeptr;
nodeptr root;
nodeptr maketree(int x);
void setleft(nodeptr p,int x);
void setright(nodeptr p,int x);
void search(int x,nodeptr p);
void inorder(nodeptr p);

main()
{
FILE *fp=fopen("binaryfile.c","r");
fscanf(fp,"%d",&x);
root=maketree(x);
while((fscanf(fp,"%d",&x))!=EOF)
search(x,root);

inorder(root);
}

void search(int x,nodeptr p)
{

if(x==(p->info)){
printf("duplicate found");
}
else if(x<(p->info))
if((p->left)==NULL)
setleft(p,x);
else search(x,p->left);
else if((p->right)==NULL)
setright(p,x);
else search(x,p->right);

}

nodeptr maketree(int x)
{
nodeptr p;
p=(struct nodetype *)malloc(sizeof(struct nodetype));
(p->info)=x;
(p->left)=NULL;
(p->right)=NULL;
return p;
}
void setleft(nodeptr p,int x)
{
if(p==NULL)
printf("error");
else if((p->left)!=NULL)
printf("/nerror");
else (p->left)=maketree(x);
}
void setright(nodeptr p,int x)
{
if(p==NULL)
printf("error");
else if((p->right)!=NULL)
printf("/nerror");
else (p->right)=maketree(x);
}
void inorder(nodeptr p)
{
if(p==NULL)
return;
else{
inorder(p->left);
printf("\n%d",p->info);
inorder(p->right);
}
return;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s