Program to find depth of a tree in C.

#include<stdio.h>
struct node
{
int info,i;
struct node* left;
struct node* right;
};
struct node* maketree(int x,int count);
void inorder(struct node*);
int rec(struct node* ,int ,int ,int );
int depth(struct node*,int ,int );
struct node* p;
int t=0,k=0;
main()
{
FILE *fp;
struct node* q;
int x,d;

fp=fopen("y.c","r");
if(fp==NULL)
{
puts("error in opening file y.c");
exit(1);
}
fscanf(fp,"%d",&x);
p= maketree(x,0);
q=p;
while((fscanf(fp,"%d",&x))>=0)
{
t=0;k=0;
rec(p,x,t,k);
p=q;
}

fclose(fp);
inorder(p);
t=0;k=0;
d=depth(p,t,k);
printf("\n depth is %d",d);

}

void inorder(struct node* p)
{
if(p==NULL)return;
inorder(p->left);
printf("\n%d",p->info);
inorder(p->right);
}
int rec(struct node* p,int x,int t,int k)
{

if((p->info)>x)
{
if(p->left==NULL){
t=++t;

setleft(p,x,t);
return(1);}
++t;
return(rec(p->left,x,t,k));
}
if((p->info)<x)
{
if(p->right==NULL){
k=++k;

setright(p,x,k);
return(1);}
++k;
return(rec(p->right,x,t,k));
}
if(p->info==x)
return(1);
}
struct node* maketree(int x,int count)
{
struct node* p;
p=(struct node*)malloc(sizeof(struct node));
p->info=x;
p->i=count;
p->left=NULL;
p->right=NULL;
return(p);
}
int setleft(struct node* p,int x,int t)
{
if(p==NULL)
puts("error");
if((p->left)!=NULL)
puts("error");
else
(p->left)=maketree(x,t);
return(1);
}
int setright(struct node* p,int x,int t)
{
if(p==NULL)
puts("error");
if((p->right)!=NULL)
puts("error");
else
(p->right)=maketree(x,t);
return(1);
}
int depth(struct node* p,int t,int k)
{
int r,s;
if(((p->left)==NULL)&&((p->right)==NULL)){
return(t+k);}
if(p->left==NULL){
t=t;++k;
return(depth(p->right,t,k));}
if(p->right==NULL){
k=k;++t;
return(depth(p->left,t,k));}
if(((p->left)!=NULL)&&((p->right)!=NULL)){
++t;
r= depth(p->left,t,k);
++k;--t;
s= depth(p->right,t,k);
if(r>=s)
return(r);
else
return(s);
}
}
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