C Fundamentals
Algorithms · data structures · cryptography · systems — pure C11, zero deps
Loading...
Searching...
No Matches
trie.c
Go to the documentation of this file.
1/**
2 * @file trie.c
3 */
4
5#include "trie.h"
6#include <ctype.h>
7#include <stdlib.h>
8#include <string.h>
9
10typedef struct trie_node {
11 struct trie_node *children[26];
14
15struct trie {
17};
18
19static trie_node_t *node_create(void) {
20 return calloc(1, sizeof(trie_node_t));
21}
22
23static void node_destroy(trie_node_t *n) {
24 if (!n) return;
25 for (int i = 0; i < 26; i++) node_destroy(n->children[i]);
26 free(n);
27}
28
30 trie_t *t = malloc(sizeof(*t));
31 if (!t) return NULL;
32 t->root = node_create();
33 if (!t->root) { free(t); return NULL; }
34 return t;
35}
36
38 if (!t) return;
40 free(t);
41}
42
43static int idx_of(char c) {
44 unsigned char u = (unsigned char)c;
45 if (u >= 'a' && u <= 'z') return u - 'a';
46 return -1;
47}
48
49bool trie_insert(trie_t *t, const char *word) {
50 if (!t || !word) return false;
51 trie_node_t *cur = t->root;
52 for (size_t i = 0; word[i] != '\0'; i++) {
53 int j = idx_of(word[i]);
54 if (j < 0) return false;
55 if (!cur->children[j]) {
56 cur->children[j] = node_create();
57 if (!cur->children[j]) return false;
58 }
59 cur = cur->children[j];
60 }
61 cur->terminal = true;
62 return true;
63}
64
65static const trie_node_t *walk(const trie_t *t, const char *s) {
66 if (!t || !s) return NULL;
67 const trie_node_t *cur = t->root;
68 for (size_t i = 0; s[i] != '\0'; i++) {
69 int j = idx_of(s[i]);
70 if (j < 0 || !cur->children[j]) return NULL;
71 cur = cur->children[j];
72 }
73 return cur;
74}
75
76bool trie_contains(const trie_t *t, const char *word) {
77 const trie_node_t *n = walk(t, word);
78 return n && n->terminal;
79}
80
81bool trie_starts_with(const trie_t *t, const char *prefix) {
82 return walk(t, prefix) != NULL;
83}
bool terminal
Definition trie.c:12
struct trie_node * children[26]
Definition trie.c:11
Definition trie.c:15
trie_node_t * root
Definition trie.c:16
bool trie_insert(trie_t *t, const char *word)
Definition trie.c:49
bool trie_contains(const trie_t *t, const char *word)
Definition trie.c:76
static int idx_of(char c)
Definition trie.c:43
struct trie_node trie_node_t
static const trie_node_t * walk(const trie_t *t, const char *s)
Definition trie.c:65
static trie_node_t * node_create(void)
Definition trie.c:19
bool trie_starts_with(const trie_t *t, const char *prefix)
Definition trie.c:81
static void node_destroy(trie_node_t *n)
Definition trie.c:23
void trie_destroy(trie_t *t)
Definition trie.c:37
trie_t * trie_create(void)
Definition trie.c:29
Prefix tree (trie) over lowercase ASCII letters a-z.