-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinSearchTree.c
133 lines (114 loc) · 2.8 KB
/
BinSearchTree.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
// Harris Ransom
// C Binary Search Tree
// Based on video by Jacob Sorber
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct treenode {
int value;
struct treenode *left;
struct treenode *right;
} treenode;
// Creates new unconnected tree node
treenode *createnode(int value) {
treenode *result = malloc(sizeof(treenode));
if (result != NULL) {
result->left = NULL;
result->right = NULL;
result->value = value;
}
return result;
}
// Outputs specified number of tabs
void printTabs(int numTabs) {
for (int i = 0; i < numTabs; i++) {
printf("\t");
}
}
// Recursively prints out tree
void printTree(treenode *root, int level) {
if (root == NULL) {
printTabs(level);
printf("---<Empty>---\n");
return;
}
// Recursive Preorder Traversal
printTabs(level);
printf("value = %d\n", root->value);
printTabs(level);
printf("left\n");
printTree(root->left, level+1);
printTabs(level);
printf("right\n");
printTree(root->right, level+1);
printTabs(level);
printf("done\n");
}
// Inserts number recursively into search tree
bool insertNum(treenode **rootp, int value) {
if (*rootp == NULL) {
*rootp = createnode(value);
return true;
}
else if (value == (*rootp)->value) {
return false;
}
else if (value < (*rootp)->value) {
return insertNum(&(*rootp)->left, value);
}
else {
return insertNum(&(*rootp)->right, value);
}
}
// Determines if number is in search tree
bool findNum(treenode *rootp, int value) {
if (rootp == NULL) {
return false;
}
else if (value == rootp->value) {
return true;
}
else if (value < rootp->value) {
return findNum(rootp->left, value);
}
else {
return findNum(rootp->right, value);
}
}
// Frees tree from memory
void deleteTree(treenode *rootp) {
if (rootp == NULL) return;
else if (rootp->left == NULL || rootp->right == NULL) {
free(rootp);
return;
}
else {
deleteTree(rootp->right);
deleteTree(rootp->left);
free(rootp);
return;
}
}
// MAIN
int main() {
// Creates binary tree
treenode *root = NULL;
// Builds tree
insertNum(&root, 15);
insertNum(&root, 11);
insertNum(&root, 24);
insertNum(&root, 5);
insertNum(&root, 16);
insertNum(&root, 19);
printTree(root, 0);
// Tests findNum
printf("%d (%d)\n", 16, findNum(root, 16));
printf("%d (%d)\n", 15, findNum(root, 15));
printf("%d (%d)\n", 15, findNum(root, 5));
printf("%d (%d)\n", 115, findNum(root, 115));
printf("%d (%d)\n", 1, findNum(root, 1));
printf("%d (%d)\n", 7, findNum(root, 7));
// Deletes tree
deleteTree(root);
return 0;
}