-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearchtree.c
More file actions
84 lines (84 loc) · 1.88 KB
/
binarysearchtree.c
File metadata and controls
84 lines (84 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct bst{
int data;
struct bst *lchild, *rchild;
};
struct bst *createbranch(int value){
struct bst *temp = (struct bst*)malloc(sizeof(struct bst));
temp->data = value;
temp->rchild = NULL;
temp->lchild = NULL;
return temp;
}
struct bst *insert(struct bst *temp, int value){
if(temp==NULL)
return createbranch(value);
if(value!=temp->data){
if(value<temp->data)
temp->lchild = insert(temp->lchild,value);
else
temp->rchild = insert(temp->rchild,value);
return temp;
}
}
struct bst *search(struct bst *temp, int value){
if(temp==NULL)
return temp;
else
{
if(temp->data==value)
return temp;
else if(value<temp->data)
return search(temp->lchild,value);
else if(value>temp->data)
return search(temp->rchild,value);
}
}
void inorder(struct bst *temp){
if(temp!=NULL){
inorder(temp->lchild);
printf("%d ->\n",temp->data);
inorder(temp->rchild);
}
}
void main()
{
int data,ch;
struct bst *branch = NULL, *search_element;
printf("Enter the base element : ");
scanf("%d",&data);
branch = insert(branch,data);
do
{
printf("Select any of the choices below : \n");
printf("1. Insert element.\n");
printf("2. Search element.\n");
printf("3. Display.\n");
printf("4. Exit.\n");
printf("Enter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter the value to be inserted : ");
scanf("%d",&data);
insert(branch,data);
break;
case 2: printf("Enter the value to be searched : ");
scanf("%d",&data);
search_element=search(branch,data);
if(search_element==NULL)
printf("Element Not Found.\n");
else if(search_element->data==data)
printf("Element Found.\n");
break;
case 3: inorder(branch);
break;
case 4: printf("EXITING.......\n");
break;
default : printf("INVALID ENRTY.\nTRY AGAIN.\n");
break;
}
}while(ch!=4);
}