aboutsummaryrefslogtreecommitdiff
path: root/trie_prefix.c
blob: 6211233ed9368d7ec6937f9bc80f6b36258745d7 (plain)
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
// 208. Implement Trie (Prefix Tree)
#include <stdbool.h>
#include <stdlib.h>

typedef struct Trie {
  struct Trie *children[26];
  bool is_leaf;
} Trie;

Trie *trieCreate() {
  Trie *node = malloc(sizeof(Trie));
  for (int i = 0; i < 26; i++)
    node->children[i] = NULL;
  node->is_leaf = false;
  return node;
}

void trieInsert(Trie *obj, char *word) {
  Trie *tmp = obj;
  for (int i = 0; word[i] != '\0'; i++) {
    int idx = word[i] - 'a';
    if (tmp->children[idx] == NULL)
      tmp->children[idx] = trieCreate();
    tmp = tmp->children[idx];
  }
  tmp->is_leaf = true;
}

bool trieSearch(Trie *obj, char *word) {
  Trie *tmp = obj;
  for (int i = 0; word[i] != '\0'; i++) {
    int idx = word[i] - 'a';
    if (tmp->children[idx] == NULL)
      return false;
    tmp = tmp->children[idx];
  }
  return tmp->is_leaf;
}

bool trieStartsWith(Trie *obj, char *prefix) {
  Trie *tmp = obj;
  for (int i = 0; prefix[i] != '\0'; i++) {
    int idx = prefix[i] - 'a';
    if (tmp->children[idx] == NULL)
      return false;
    tmp = tmp->children[idx];
  }
  return true;
}

void trieFree(Trie *obj) {
  Trie *tmp = obj;
  for (int i = 0; i < 26; i++)
    if (tmp->children[i] != NULL)
      trieFree(tmp->children[i]);
  free(obj);
}

int main() {
  Trie *obj = trieCreate();
  trieInsert(obj, word);
  bool param_2 = trieSearch(obj, word);
  bool param_3 = trieStartsWith(obj, prefix);
  trieFree(obj);
}