C Program to Implement Binary Search Tree Traversal
#include
#include
#include
typedef
struct Bst
{
int data;
struct Bst*lchild,*rchild;
}
node;
void
insert(node*,node);
void
inorder(node*);
void
preorder(node*);
void
postorder(node*);
node*search(node*,int,node**);
void
main()
{
int
choice;
char
ans=’N’;
int key;
node*new_node,
*root, *tmp, *parent;
node*get_node();
root=NULL;
clrscr();
printf("\n Program for binary search tree");
do
{
printf("\n1.Create”);
printf("\n2. Search");
printf("\n3. Recursive Traversals");
printf("\n4. Exit");
printf("\n Enter your choice:”);
scanf("%d",&choice);
switch (chice)
{
case 1:
do
{
New_node=get_node();
printf("\n Enter the element");
scanf(“%d”,&new_node->data);
if(root==NULL)
root=new_node;
else
insert(root,new_node);
printf("\n Want to enter more
elements?(y/n) ");
ans=getch();
}
while(ans==’y’);
break;
case 2:
printf("\n Enter element to be
searched:”);
scanf(“%d”,&key);
tmp=search(root,key,&parent);
printf("\n Parent of node
%d",tmp->data,parent->data);
break;
case 3:
if(root==NULL)
printf(“Tree is not created");
else
{
printf("\n The inorder display: ");
inorder(root);
printf("The preorder display:”);
preorder(root);
printf("\n The postorder display:”);
postorder(root);
}
break;
}
}
while(choice!=4)
}
node*get_node()
node*temp;
temp=(node*)malloc(sizeof(node));
temp->lchild=null;
temp->rchild=null;
return temp;
}
void insert (node*root,node*new_node)
{
if(new_node->datadata)
{
if(root->lchild==NULL)
root->lchild=new_node;
else
insert(root->lchild=new_node);
}
if(nw_node->data>root->data)
{
if (root->rchild==NULL)
root->rchild=new_node;
else
insert(root->rchild,wnew_node);
}
}
node*search(node*root,int ky, node**parent)
{
node*temp;
temp=root;
while(temp!NULL)
{
if(temp->data==key)
{
printf("\n The %d element is present”,
temp->data);
return temp;
}
parent=temp;
if(temp->data>key)
temp=temp->lchild;
else
temp=temp->rchild;
}
return NULL;
}
void inorder(node*temp)
{
if(temp!=NULL)
{
inorder(temp->lchild);
printf("%d”,temp->data);
inorder(temp->rchild);
}
}
void preorder(node*temp)
{
if(temp!=NULL)
{
printf("%d”,temp->data);
preorder(temp->lchild);
inorder(temp->rchild);
}
}
void postorder(node*temp)
{
if(temp!=NULL)
{
postorder(temp->lchild);
postorder(temp->rchild);
printf("%d”,temp->data);
}
}
No comments:
Post a Comment