-
Notifications
You must be signed in to change notification settings - Fork 1
/
binary_search_tree.c
82 lines (73 loc) · 1.66 KB
/
binary_search_tree.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <stdbool.h> // required for type bool
typedef struct node{
int number;
struct node *left;
struct node *right;
}
node;
//binary search
bool search(node *tree, int num){
if(tree == NULL){
return false; //end of leaf
}
if(tree -> number < num){
return search(tree -> right, num);
}
else if(tree -> number > num){
return search(tree -> left, num);
}
else{
return true; // found
}
}
void addNode(node *tree, int num){
if(tree == NULL){
return;
}
node *n = malloc(sizeof(node));
if(n == NULL){
return;
}
//add the number to newely created node
n -> number = num;
//add to right
if(num > tree -> number){
if(tree -> right == NULL)
tree -> right = n;
else
addNode(tree -> right, num);
}
//add to left
else if(num < tree -> number){
if(tree -> left == NULL)
tree -> left = n;
else
addNode(tree -> left, num);
}
}
int main(void){
//create root node
node *tree = malloc(sizeof(node));
tree -> number = 10;
tree -> left = NULL;
tree -> right = NULL;
addNode(tree, 2);
addNode(tree, 9);
addNode(tree, 2);
addNode(tree, 6);
addNode(tree, 23);
addNode(tree, 34);
addNode(tree, 43);
addNode(tree, 56);
addNode(tree, 12);
int lookingFor = get_int("Enter the number you want to search in the tree: ");
if(search(tree, lookingFor) == true){
printf("found %i\n", lookingFor);
}else{
printf("not found %i\n", lookingFor);
}
return 0;
}