Binary search tree


Program to perform binary tree construction...
Inorder traverse technique used to display the nodes of the tree..
Sample output for the program is given above.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<alloc.h>
struct node
{
int info;
struct node *left,*right;
};
typedef struct node *nodeptr;
nodeptr getnode()
{
nodeptr p;
p=(nodeptr)malloc(sizeof(struct node));
return p;
}
nodeptr maketree(int x)
{
nodeptr p;
p=getnode();
p->info=x;
p->left=NULL;
p->right=NULL;
return p;
}

void setleft(nodeptr p,int x)
{
nodeptr q;
if(p==NULL||p->left!=NULL)
printf("\nInvalid operation..!");
else
{
q=maketree(x);
p->left=q;
}
}
void setright(nodeptr p,int x)
{
nodeptr q;
if(p==NULL||p->right!=NULL)
printf("\nInvalid operation..!");
else
{
q=maketree(x);
p->right=q;
}
}
void inorder(nodeptr p)
{
if(p!=NULL)
{
inorder(p->left);
printf("%d\t",p->info);
inorder(p->right);
}
}
main()
{
int ele,i;
nodeptr p,q,root;
clrscr();
printf("Insertion of element into the tree\n");
printf("\nEnter the root node element : ");scanf("%d",&ele);
printf("\nNode values accepted untill cltr+z is pressed..\n");
root=maketree(ele);
while(scanf("%d",&ele)!=EOF)
{
p=q=root;
while(p->info!=ele && q!=NULL)
{
p=q;
if(ele>p->info)
q=p->right;
else
q=p->left;
}
if(p->info==ele)
printf("Duplicate element entered..!\n");
else
if(ele<p->info)
setleft(p,ele);
else
setright(p,ele);
}
printf("\n +***--TREE--***+\n\n");
inorder(root);
getch();
return 0;
}
Category:

0 comments: