Trie树C语言实现

it2025-09-25  4

实现了输入单词,判断单词是否存在以及是否存在该单词的前缀

#include <string.h> #include <stdlib.h> #include <stdio.h> typedef struct trie { int isEnd; struct trie *next[26]; } Trie; Trie * trieCreate() { Trie *root = (Trie *)malloc(sizeof(Trie)); memset(root, 0, sizeof(*root)); root->isEnd = 0; return root; } void trieInsert(Trie *obj, char *word) { Trie *node = obj; for (int i = 0; word[i] != '\0'; i++) { char c = word[i]; if (node->next[c - 'a'] == NULL) node->next[c - 'a'] = trieCreate(); node = node->next[c - 'a']; } node->isEnd = 1; } bool trieSearch(Trie *obj, char *word) { Trie *node = obj; for (int i = 0; word[i] != '\0'; i++) { char c = word[i]; if (node->next[c - 'a'] == NULL) return false; node = node->next[c - 'a']; } return node->isEnd > 0; } bool trieStartsWith(Trie *obj, char *prefix) { Trie *node = obj; for (int i = 0; prefix[i] != '\0'; i++) { char c = prefix[i]; if (node->next[c - 'a'] == NULL) return false; node = node->next[c - 'a']; } return true; } void trieFree(Trie *obj) { if (obj == NULL) return; for (int i = 0; i < 26; i++) { if (obj->next[i]) trieFree(obj->next[i]); } free(obj); } int main() { Trie *root = trieCreate(); char word[50]; while (scanf("%s", word) != EOF) { trieInsert(root, word); } char a[50]; while (scanf("%s", a) != EOF) { if (trieStartsWith(root, a)) printf("Yes\n"); else printf("No\n"); } return 0; }

代码参考 https://leetcode-cn.com/problems/implement-trie-prefix-tree/solution/c-zhi-xing-yong-shi-48ms-108ms-nei-cun-377mb-by-xu/

最新回复(0)