trie树也叫字典树,搜索树等。
如图所示
下面是用stl 的map来实现
class trie_item_c { public: trie_item_c(){} trie_item_c(const char nm) { name = nm; } void set_name(const char nm) { name = nm; } trie_item_c * get_child(const char nm) { map<const char ,trie_item_c*>::const_iterator it = children.find(nm); if(it != children.end()) return it->second; else { trie_item_c *cld = new trie_item_c(nm); children.insert(pair <const char ,trie_item_c*>(nm,cld)); return cld; } } bool find(const char* dic) { if(!dic || *dic == '\0') { if(children.end() != children.find('\0')) return true; return false; } const char* temp = dic; map<const char ,trie_item_c*>::const_iterator it = children.find(*temp); if(it == children.end()) return false; return it->second->find(++temp); } void print() { printf("%c",name); map<const char ,trie_item_c*>::const_iterator it = children.begin(); for(;it != children.end();it++) { it->second->print(); } printf("\n"); } virtual ~trie_item_c() { map<const char ,trie_item_c*>::const_iterator it = children.begin(); while(it != children.end()) { delete it->second; children.erase(it); it = children.begin(); } } private: map<const char ,trie_item_c*> children; char name; };
下面代码是构建树的过程
for(const char* dic = lst.first_string();dic;dic = lst.next_string()) { trie_item_c *temp = root; for(int i=0;i<str_temp.str_len();i++) { char c = str_temp.get(i); trie_item_c *item = temp->get_child(c); temp = item; } //add one null child temp->get_child('\0'); }
原文地址:http://blog.csdn.net/zhanghaiyang9999/article/details/41219047