字符串应用:不仅仅为字符串字典,还可以数字,二进制字典等
声明结构体字典树节点
struct TrieNode
{
int word;
struct TrieNode *next[26];
};
字典树节点初始化
TrieNode *CreateTrieNode()
{
TrieNode *p=(TrieNode *)malloc(sizeof(TrieNode));
p->word=0;
for (int i=0;i<26;i++)
p->next[i]=NULL;
return p;
}
插入字符串
void Insert(char *str)
{
TrieNode *p=root;
int len=strlen(str);
for (int i=0;i<len;i++)
{
int id=str[i]-'a';
if (p->next[id] == NULL)
{
p->next[id]=CreateTrieNode();
p=p->next[id];
}
else p=p->next[id];
}
p->word=1;
}
查找字符串
int Find()//视题目情况来写查找标程
{
Trie *root=p;
int len=strlen(str);
for (int i=0;i<len;i++)
{
int id=str[i]-'a';
if (root->next[id] == NULL) return 0;
else root=root->next[id];
}
return root->value;
}
删除字典树(后序遍历)
void de(node *p)
{
if(p==0)
return ;
int i;
for(i=0;i<26;i++)
{
de(p->next[i]);
}
delete p; //free
}