To following program will calculate the depth of a tree:-
# include< stdio.h>
# include< stdlib.h>
#include< conio.h>
struct node
{
int info;
struct node *left;
struct node *right;
};
int d=0;
int depth (struct node *n, int level)
{
if (n != NULL)
{
if (level > d)
d = level;
depth (n->left,level + 1);
depth (n->right,level + 1);
}
return (d);
}
struct node * create()
{
struct node *node;
int x;
node=(struct node *)malloc(sizeof(struct node));
printf("\nEnter the value:-");
scanf("%d",&x);
node->info=x;
node->left=NULL;
node->right=NULL;
return node;
}
struct node *add(struct node *t,struct node *root)
{
if(root==NULL)
{
root=t;
return root;
}
else
{
if(t->info<=root->info)
{
root->left=add(t,root->left);
printf("\nAdded to left of node %d",root->info);
}
else
{
root->right=add(t,root->right);
printf("\nAdded to right of node %d",root->info);
}
return root;
}
}
void output(struct node *t, int level)
{
int i;
if (t)
{
output(t->right, level+1);
printf("\n");
for (i = 0; i < level; i++)
printf(" ");
printf("%d,%d (level)", t->info,level);
printf("\n");
output(t->left, level+1);
}
}
void main()
{
int info,d,xx=0;
char choice='y';
struct node *t,*root=NULL,*rr;
clrscr();
while(choice != 'n')
{
t=create ();
if(xx==0)
rr=t;
xx++;
printf("\n Tree is ");
root=add(t,root);
output(rr,0);
fflush(stdin);
printf("\n Enter choice--'n' to break:");
scanf("%c",&choice);
}
d = depth(rr, 0);
printf("\n Depth of the above tree is: %d", d);
getch();
Sir please tell about the usage of linked lists in bluej
ReplyDeleteWhen array fails, linked list is used in java. LinkedList is fully dynamic and insertion and deletion can be done perfectly.
Delete