forked from Privanom/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BST.c
67 lines (59 loc) · 2.05 KB
/
BST.c
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
// Implementation of Binary Search Tree
#include <stdio.h>
#include <stdlib.h>
struct BST {
int data;
struct BST* left;
struct BST* right;
};
struct BST *CreateNode() {
struct BST* new = (struct BST*) malloc(sizeof(struct BST));
new->left = NULL;
new->right = NULL;
return new;
};
void Insert(struct BST** RootPtr, int value) {
struct BST* temp = *RootPtr;
if (temp == NULL) { /*When list is empty*/
struct BST* NewNode = CreateNode();
NewNode->data = value;
*RootPtr = NewNode;
} else if (value <= temp->data) { /*If user value is less then current node value insert in left of the node...*/
struct BST* NewNode = CreateNode();
NewNode->data = value;
temp->left = NewNode;
} else { /*If user value is greater then current node value insert at right of the node*/
struct BST* NewNode = CreateNode();
NewNode->data = value;
temp->right = NewNode;
}
}
int Search(struct BST* RootPtr, int item) { /*Implemented search using recursion*/
if(RootPtr == NULL) {
return 0; /*Returns 0 if list is empty*/
} else if(item == RootPtr->data) {
return 1; /*Returns 1 when element found*/
} else if(item < RootPtr->data) {
Search(RootPtr->left, item); /*Otherwise search in left side of binary tree if searching value is less then the current node value*/
} else {
Search(RootPtr->right, item); /*Otherwise search in right side of binary tree if searching value is greater then the current node value*/
}
}
void main() {
struct BST* RootPtr = NULL;
int item, cont, key;
do {
printf("Enter item: ");
scanf("%d",&item);
Insert(&RootPtr, item);
printf("\n1 to keep inserting/ 0 to Exit: ");
scanf("%d",&cont);
} while(cont == 1);
printf("\nEnter element to search: ");
scanf("%d",&key);
if(Search(RootPtr, key) == 0) {
printf("\nFound\n");
} else {
printf("\nNot Found\n");
}
}