Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Name of the Program:week6

Week 6:Write a C program that uses functions to perform the following:


a) Create a binary search tree of integers.
b) Traverse the above Binary search tree non recursively in inorder
return;
#include <stdio.h>
#include <stdlib.h>
struct BST
{
int data;
struct BST *left,*right;
}node;
//structure of a stack node
//stack node contains a pointer to tree node
and pointer to next stack node
struct stack
{
struct BST*t;
struct stack*next;
};
struct BST* root=NULL,*temp,*cur;
void create()
{
temp=root;
cur=(struct BST*)malloc(sizeof(struct
BST));
printf("\n enter integer value:\n");
scanf("%d",&cur->data);
cur->left=NULL;
cur->right=NULL;
if(temp==NULL)
root=cur;
else
{
while(temp!=NULL)
{
if((cur->data)<(temp->data))
{
if(temp->left==NULL)
{
temp->left=cur;
return;
}
else
temp=temp->left;
}
else
{
if(temp->right==NULL)
{
temp->right=cur;

}
else
temp=temp->right;
}//else
}//while
}//else
}//create
void push(struct stack**top,struct BST*t)
{
struct stack*new=(struct
stack*)malloc(sizeof(struct stack));
if(new==NULL)
{
printf("\n stack overflow");
return;
}
new->t=t;
new->next=(*top);
(*top)=new;
}
int isempty(struct stack*top)
{
return(top==NULL)?1:0;
}
struct BST* pop(struct stack**top)
{
struct BST *res;
struct stack *top1;
if(isempty(*top))
printf("\n stack underflow");
else
{
top1=*top;
res=top1->t;
*top=top1->next;
free(top1);
return res;
}
}
void inorder(struct BST *root)
{
struct BST *cur=root;
struct stack *s=NULL;
while (1)
{

Name of the Program:week6


if (cur != NULL)
{
push(&s,cur);
cur=cur->left;
}
else
{
if (!isempty(s))
{
cur=pop(&s);
printf("\t%d",cur->data);
cur=cur->right;
}
else
break;
}
}
}
int main()
{
int ch;
printf("\nmenu options\n");
printf("1.Create\n2.inorder\n3.exit\n");
while(1)
{
printf("\nenter ur choice");
scanf("%d",&ch);
switch(ch)
{
case 1:create();
break;
case 2:printf("inorder
Traversal\n");
inorder(root);
break;
case 3:exit(0);
default:printf("invalid
choice\n");
}//switch
}//while
}//main
Output:
]$ ./a.out

menu options
1.Create
2.inorder
3.exit
enter ur choice1
enter integer value:
43
enter ur choice1
enter integer value:
20
enter ur choice1
enter integer value:
56
enter ur choice1
enter integer value:
15
enter ur choice1
enter integer value:
18
enter ur choice1
enter integer value:
45
enter ur choice1
enter integer value:
65
enter ur choice2
inorder Traversal
15
18
20
43
45
56
enter ur choice3
[13r21a0507@mysqldbserver week6]$

65

You might also like