数组模拟trie树c语言
时间: 2023-08-28 12:05:06 浏览: 100
C语言树数组
以下是使用数组模拟trie树的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRIE_SIZE 26
typedef struct TrieNode {
int is_end;
struct TrieNode *next[TRIE_SIZE];
} TrieNode;
TrieNode *create_node() {
TrieNode *node = (TrieNode *) malloc(sizeof(TrieNode));
node->is_end = 0;
for (int i = 0; i < TRIE_SIZE; i++) {
node->next[i] = NULL;
}
return node;
}
void insert(TrieNode *root, char *word) {
TrieNode *node = root;
int len = strlen(word);
for (int i = 0; i < len; i++) {
int index = word[i] - 'a';
if (node->next[index] == NULL) {
node->next[index] = create_node();
}
node = node->next[index];
}
node->is_end = 1;
}
int search(TrieNode *root, char *word) {
TrieNode *node = root;
int len = strlen(word);
for (int i = 0; i < len; i++) {
int index = word[i] - 'a';
if (node->next[index] == NULL) {
return 0;
}
node = node->next[index];
}
return node->is_end;
}
int main() {
char *words[] = {"apple", "banana", "orange", "grape", "watermelon"};
TrieNode *root = create_node();
for (int i = 0; i < 5; i++) {
insert(root, words[i]);
}
printf("%d\n", search(root, "apple"));
printf("%d\n", search(root, "watermelon"));
printf("%d\n", search(root, "peach"));
return 0;
}
```
在上述代码中,每个节点都有一个 `next` 数组,用于保存下一个字符对应的节点指针。在插入和查找时,遍历输入的字符串,根据每个字符找到对应的节点,如果节点不存在则创建新的节点。最后一个节点标记为单词结尾。
阅读全文