C语言trie树问题
先贴上原码,这是在网上找到
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
typedef struct Trie_node_stru
{
int count; //记录该处终结的单词个数
struct Trie_node_stru *next[26];//指向各个子树的指针,下标0-25代表26字符
}TrieNode, *Trie;
TrieNode* trie_createTrieNode()
{
TrieNode* tmp = (TrieNode*)malloc(sizeof(TrieNode));
tmp->count = 0;
memset(tmp->next, 0, sizeof(tmp->next));
return tmp;
}
int trie_insert(Trie root, char* word)
{
TrieNode* node = root;
char *p = word;
while(*p)
{
if(NULL == node->next[*p-'a'])
{
node->next[*p-'a'] = trie_createTrieNode();
}
node = node->next[*p-'a'];
p++;
}
node->count += 1;
printf("%-20s appears for %d time(s) in the Trie!\r\n",
word, node->count);
return 0;
}
int trie_search(Trie root, char* word)
{
TrieNode* node = root;
char *p = word;
while(*p && NULL!=node)
{
node = node->next[*p-'a'];
p++;
}
return (node!=NULL && node->count>0);
}
int trie_remove(Trie root, char* word)
{
//TODO
return 0;
}
int main()
{
Trie t = trie_createTrieNode();
trie_insert(t, "a");
trie_insert(t, "abc");
char * c = "test";
trie_insert(t, c);
trie_insert(t, "testonly");
trie_insert(t, "testonly");
trie_insert(t, "a");
printf("====================\r\n");
if(trie_search(t, "a"))
printf("true\n");
else
printf("false\n");
if(trie_search(t, "testnly"))
printf("true\n");
else
printf("false\n");
return 0;
}
======================================================================================================
trie_insert函数中的node->next[*p-'a']变成node->next[*p]
trie_search函数中的node->next[*p-'a']变成node->next[*p]后
再编译运行,输出结果为false,请大吓们给讲讲,为啥把'a'去掉后就变成false了
[解决办法]
汗,当然要加上-'a'了。因为加入当前字母为'b',那它就应该在next[1]的位置,不减就是b的ascii码即next[98]
[解决办法]
node = node->next[*p-'a'];
>>next是指针数组,*p-'a'是下标,范围0-25,不减可能就越界了
[解决办法]