-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trie Tree
83 lines (74 loc) · 1.94 KB
/
Trie Tree
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
#define MAX 26
struct TrieNode {
int count;
char ch;
struct TrieNode * child[MAX];
};
/** Initialize your data structure here. */
struct TrieNode* trieCreate() {
int i;
struct TrieNode * pt = (struct TrieNode *)malloc(sizeof(struct TrieNode));
pt->ch = ' ';
pt->count = 0;
for(i=0;i<MAX;i++)
pt->child[i] = NULL;
return pt;
}
struct TrieNode * createTrieNode(char c){
int i;
struct TrieNode * pt = ( struct TrieNode *)malloc(sizeof( struct TrieNode));
pt->ch = c;
pt->count = 0; //记录单词数量及是否为有效单词
for(i=0;i<MAX;i++)
pt->child[i] = NULL;
return pt;
}
/** Inserts a word into the trie. */
void insert(struct TrieNode* root, char* word) {
struct TrieNode * pt = root;
while(*word){
if( pt->child[ *word - 'a' ] == NULL )
pt->child[*word - 'a'] = createTrieNode(*word);
pt = pt->child[ *word - 'a' ];
word ++;
}
pt->count++;
}
/** Returns if the word is in the trie. */
bool search(struct TrieNode* root, char* word) {
struct TrieNode * pt = root;
while(*word){
if( pt->child[ *word - 'a' ] == NULL )
break;
pt = pt->child[*word - 'a'];
word ++;
}
if( (*word == '\0') && (pt->count > 0) )
return true;
else
return false;
}
/** Returns if there is any word in the trie
that starts with the given prefix. */
bool startsWith(struct TrieNode* root, char* prefix) {
struct TrieNode * pt = root;
while(*prefix){
if( pt->child[ *prefix - 'a' ] == NULL )
break;
pt = pt->child[*prefix - 'a'];
prefix ++;
}
if( *prefix == '\0' )
return true;
else
return false;
}
/** Deallocates memory previously allocated for the TrieNode. */
void trieFree(struct TrieNode* root) {
int i;
if( !root )
return ;
for(i=0;i<MAX;i++)
trieFree(root->child[i]);
free(root);
}