Trie树及其应用
Trie树
Trie树,又称单词查找树、字典树,是一种树形结构,是一种哈希树的变种,是一种用于快速检索的多叉树结构。典型应用是用于统计和排序大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。
Trie树的优点是:最大限度地减少无谓的字符串比较,查询效率比哈希表高。 Trie的核心思想是空间换时间。利用字符串的公共前缀来降低查询时间的开销以达到提高效率的目的。 Trie树也有它的缺点,Trie树的内存消耗非常大.
Trie树的结构特点:
1.root结点没有数据
2.除根结点外每个结点只包含一个字符
3.从根结点到某一个结点正好组成一个字符串
Trie树的大致结构如下:
Trie树的实现
下面是一个简单的Trie树的实现,假定只包括26个字符,忽略大小写。
1
|
|
#include <stdlib.h> class Trie{ public: Trie(); ~Trie(); int insert(const char* str); int search(const char* str)const; int remove(const char* str); static const int CharNum = 26; protected: typedef struct s_Trie_Node{ bool isExist; struct s_Trie_Node* branch[Trie::CharNum]; s_Trie_Node(); }Trie_Node; Trie_Node* root; }; Trie::Trie():root(NULL){} Trie::~Trie(){} Trie::s_Trie_Node::s_Trie_Node():isExist(false){ for(int i = 0; i < Trie::CharNum; ++i){ branch[i] = NULL; } } int Trie::insert(const char* str){ if(root == NULL){ root = new Trie_Node(); } Trie_Node* pos = root; int char_pos; while(pos != NULL && *str != '