Algorithm and Program - Recursive algorithm to
create binary tree
create_tree(info,node)
Where
info ->
Information for node in tree
node -> Structure type variable to points both
left and right child.
Step -1 [Check whether the tree is empty ]
If node=NULL
Node=create
node
Left_child[node]=NULL
Right_child[node]=NULL
Return
(node)
Step- 2 [Test for the left child]
if
info[node] >=info
Left_child[node]=call create_tree(info,Left_child[node])
else
right_child[node]=call
create_tree(info,right_child[node])
Step-3 return(node)
Program
// Create binary tree
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct tree
{
int no;
struct tree
*left;
struct tree
*right;
};
struct tree * create_tree(int n,struct tree *node)
{
if(node==NULL)
{
printf("\n
n= %d",n);
node=(struct
tree *)malloc(sizeof(struct tree));
node->no=n;
node->left=NULL;
node->right=NULL;
return(node);
}
if(node->no >= n)
{
node->left=create_tree(n,node->left);
}
else
{
node->right=create_tree(n,node->right);
}
return(node);
}
void
output(struct tree *t,int level)
{
int i;
if(t)
{
output(t->right,level+1);
printf("\n
");
for(i=0;i<level;i++)
{
printf(" ");
}
printf("%d",t->no);
printf("\n");
output(t->left,level+1);
}
}
void main()
{
int d;
char
ch;
struct
tree *t=(struct tree *)malloc(sizeof(struct tree *));
clrscr();
t=NULL;
printf("\n
Enter n for break : ");
ch=getchar();
while(ch
!= 'n')
{
printf("\n
Enter number : ");
scanf("%d",&d);
t=create_tree(d,t);
printf("\n output ");
output(t,1);
fflush(stdin);
printf("\n Enter n for break : ");
ch=getchar();
}
getch();
}
Posted By : Ruchita Pandya
No comments:
Post a Comment