trie树简介

trie树:又名字典树,是以空间换时间的字符树

 

trie树示例:(手绘)

 

trie树的操作:

create a trie insert a word find a word destroy a trie

trie树的数据结构:以字符只有26个英文字母为例,静态分配空间

struct Trie{ int num; //how many words can reach here bool terminal; //terminal = true:the end of word struct Trie* son[26]; //动态分配空间 //存储字/字符 };

trie树操作的程序实现(c ++):

1:create a trie

Trie * createTrie() { Trie * root = new Trie(); root->num = 0; root->terminal = false; for(int i = 0; i < 26; i++) { root->son[i] = NULL; } return root; }

2:insert a word

void insert(Trie* root, char* word, int len) { Trie* tmp = root; for(int i = 0; i < len; i++) { if(root->son[word[i]-'a'] == NULL) { root->son[word[i]-'a'] = new Trie(); } else { root->son[word[i]-'a']->num++; } tmp = tmp->son[word[i]-'a']; } tmp->terminal = true; }

3:find a word

bool find(Trie* root, char* str, int len) { Trie* tmp = root; for(int i = 0; i < 26; i++) { if(tmp->son[str[i]-'a'] != NULL) { tmp = tmp->son[str[i]-'a']; } else { break; } } if(i == 26) { return true; } else { return false; } }

4:destroy a node

void destroyTrie(Trie* root) { for(int i = 0; i < 26; i++) { if(root->son[i] != NULL) { delete(root->son[i]); } } delete root; root = NULL; }

分析:

1:对于trie树,消耗内存大,第i层的节点数为26i

2:便于查询字符串的前缀

3:插入word和查找word的时间复杂度:o(word的长度)

4:扩展数据结构,以适用多种字符集

 

 

 

你可能感兴趣的:(数据结构,struct,null,delete,insert,Terminal)