-
Notifications
You must be signed in to change notification settings - Fork 411
/
Copy pathtrie.c
118 lines (94 loc) Β· 2.01 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
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
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "trie.h"
struct trie_node
{
bool is_leaf;
struct trie_node *children[MAX_CHILDREN_LENGTH];
};
/**
* Creates and initializes a new trie node.
*/
trie_t trie_create(void)
{
trie_t node = malloc(sizeof(struct trie_node));
if (node == NULL)
{
return NULL;
}
// a new node is not a leaf node by default
node->is_leaf = false;
// initialize children pointers to NULL
for (int i = 0; i < MAX_CHILDREN_LENGTH; i++)
{
node->children[i] = NULL;
}
return node;
}
unsigned int hash(const char letter)
{
// assign the last position to the apostrophe
if (letter == '\'')
{
return MAX_CHILDREN_LENGTH - 1;
}
// ignore case by converting the given letter to lowercase
return tolower(letter) - 97;
}
/**
* Inserts a new node into the trie at the right place under key.
*/
bool trie_insert(trie_t root, const char *key)
{
trie_t node = root;
for (int i = 0, length = strlen(key); i < length; i++)
{
unsigned int h = hash(key[i]);
// create new node if necessary
if (node->children[h] == NULL)
{
node->children[h] = trie_create();
}
node = node->children[h];
// insufficient memory
if (!node)
{
return false;
}
}
node->is_leaf = true;
return true;
}
/**
* Searches the trie structure for the key, starting at root node.
*/
bool trie_find(trie_t root, const char *key)
{
trie_t node = root;
for (int i = 0, length = strlen(key); i < length; i++)
{
int h = hash(key[i]);
node = node->children[h];
if (!node)
{
return false;
}
}
return node->is_leaf;
}
/**
* Frees the whole tree.
*/
void trie_free(trie_t root)
{
if (root == NULL)
{
return;
}
for (int i = 0; i < MAX_CHILDREN_LENGTH; i++)
{
trie_free(root->children[i]);
}
free(root);
}