普通Trie
const int ALPHABETS=26;
struct TrieNode {
TrieNode *c[ALPHABETS];
bool f;
TrieNode():f(false) {
memset(c,0,sizeof c);
}
~TrieNode() {
for(int i=0;i<ALPHABETS;i++)
if(c[i])
delete c[i];
}
void insert(const char *key) {
if((*key)==0) {
f=true;
} else {
int Next=((*key)-'A');
if(c[Next]==NULL) {
c[Next]=new TrieNode();
}
c[Next]->insert(key+1);
}
}
TrieNode *find(const char *key) {
if((*key)==0) {
if(f)
return this;
else return NULL;
}
int Next=((*key)-'A');
if(c[Next]==NULL) return NULL;
return c[Next]->find(key+1);
}
};
左儿子右兄弟
struct TrieNode {
bool f;
TrieNode *lc,*rb;
char ch;
TrieNode():f(false),lc(0),rb(0),ch(0) {}
~TrieNode() {
delete lc;
delete rb;
}
void insert(const char *key) {
if((*key)==0) {
f=true;
} else {
TrieNode *pos=lc,*lastpos=0;
while(pos!=NULL) {
if(pos->ch==(*key)) break;
lastpos=pos;
pos=pos->rb;
}
if(pos==NULL) {
pos=new TrieNode();
pos->ch=(*key);
if(lastpos!=NULL)
lastpos->rb=pos;
}
if(lc==NULL) lc=pos;
pos->insert(key+1);
}
}
TrieNode *find(const char *key) {
if((*key)==0) {
if(this->f)
return this;
else return NULL;
}
TrieNode *pos=lc;
while(pos!=NULL && pos->ch!=(*key))
pos=pos->rb;
if(pos==NULL) return NULL;
else return pos->find(key+1);
}
};