//字典树的实现
#include<iostream>
using namespace std;
const int num=26;
struct trie_node{
trie_node():is_word(false){
for(int i=0;i<26;i++)
child[i]=NULL;
}
trie_node* child[26];
bool is_word;
};
class Trie{
public:
Trie():root(NULL){}
trie_node* root;
void insert(char* str);
bool del(char* str);
bool search(char* str);
};
//向字典树中插入字段
void Trie::insert(char* str){
if(root==NULL)
root=new trie_node();
trie_node* tmp=root;
while(*str!='\0'){
if(tmp->child[*str-'a']==NULL)
tmp->child[*str-'a']=new trie_node;
tmp=tmp->child[*str-'a'];
str++;
}
tmp->is_word=true;
}
//字典树中删除字典,其实是将is_word置为false
bool Trie::del(char* str){
trie_node* tmp=root;
while(*str!='\0'){
if(tmp->child[*str-'a']==NULL)
return false;
tmp=tmp->child[*str-'a'];
str++;
}
if(tmp->is_word)
tmp->is_word=false;
else
return false;
return true;
}
//字典树的搜索
bool Trie::search(char* str){
trie_node* tmp=root;
while(*str!='\0'){
if(tmp->child[*str-'a']==NULL)
return false;
tmp=tmp->child[*str-'a'];
str++;
}
return tmp->is_word;
}
int main(){
Trie tr;
tr.insert("abc");
cout<<tr.search("abc")<<endl;
tr.del("abc");
cout<<tr.search("abc")<<endl;
system("pause");
return 0;
}
字典树的动态实现
最新推荐文章于 2022-03-07 00:19:57 发布