-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtrie.c
83 lines (71 loc) · 2.06 KB
/
trie.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define NUM_CHARS 256 // (size of a byte)
typedef struct trie_node {
struct trie_node* children[NUM_CHARS];
bool terminal;
} trie_node;
trie_node* create_node() {
trie_node* node = (trie_node*)malloc(sizeof(trie_node));
if (node == NULL) {
fprintf(stderr, "Error: Unable to allocate memory for trie node\n");
exit(1);
}
node->terminal = false;
for (int i = 0; i < NUM_CHARS; i++) {
node->children[i] = NULL;
}
return node;
}
bool trie_insert(trie_node** root, const char* value) {
if (*root == NULL) {
*root = create_node();
}
// char is signed so can be negative but we don't want negative index values.
unsigned char* u_value = (unsigned char*) value;
trie_node* current = *root;
int len = strlen(value);
for (int i = 0; i < len; i++) {
// Create a node for the character if it doesn't exist
if (current->children[u_value[i]] == NULL) {
current->children[u_value[i]] = create_node();
}
// Set the current node to the child node that was created or already existed
current = current->children[u_value[i]];
}
if (current->terminal) {
return false;
} else {
current->terminal = true;
return true;
}
}
void print_trie(trie_node* root, char* prefix, int depth) {
if (root == NULL) {
printf("Trie is empty\n");
return;
}
if (root->terminal) {
prefix[depth] = '\0';
printf("%s\n", prefix);
}
for (int i = 0; i < NUM_CHARS; i++) {
if (root->children[i] != NULL) {
prefix[depth] = i;
print_trie(root->children[i], prefix, depth + 1);
}
}
}
int main(int argc, char** argv) {
printf("Trie data structure example\n");
trie_node* root = NULL;
trie_insert(&root, "cow");
trie_insert(&root, "dog");
trie_insert(&root, "dad");
trie_insert(&root, "cat");
char prefix[100];
print_trie(root, prefix, 0);
return 0;
}