一般的多插树结构如下:
struct TreeNode {VALUETYPE value; //结点值TreeNode* children[NUM]; //指向孩子结点};
而 Trie 的结点是这样的(假设只包含’a’~’z’中的字符):
struct TrieNode {bool isEnd; //该结点是否是一个串的结束TrieNode* next[26]; //字母映射表};
TrieNode* next[26]中保存了对当前结点而言下一个可能出现的所有字符的链接
字典树的特性:
- Trie 的形状和单词的插入或删除顺序无关,也就是说对于任意给定的一组单词,Trie 的形状都是唯一的。
- 查找或插入一个长度为 L 的单词,访问 next 数组的次数最多为 L+1,和 Trie 中包含多少个单词无关。
- Trie 的每个结点中都保留着一个字母表,这是很耗费空间的。如果 Trie 的高度为 n,字母表的大小为 m,最坏的情况是 Trie 中还不存在前缀相同的单词,那空间复杂度就为 O(m^n)。
208. 实现 Trie (前缀树)
实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
示例:
Trie trie = new Trie();trie.insert("apple");trie.search("apple"); // 返回 truetrie.search("app"); // 返回 falsetrie.startsWith("app"); // 返回 truetrie.insert("app");trie.search("app"); // 返回 true
实现:
class Trie {private:bool isEnd;Trie* next[26];public:Trie() {isEnd = false;memset(next, 0, sizeof(next));}void insert(string word) {Trie* node = this;for (char c : word) {if (node->next[c-'a'] == NULL) {node->next[c-'a'] = new Trie();}node = node->next[c-'a'];}node->isEnd = true;}bool search(string word) {Trie* node = this;for (char c : word) {node = node->next[c - 'a'];if (node == NULL) {return false;}}return node->isEnd;}bool startsWith(string prefix) {Trie* node = this;for (char c : prefix) {node = node->next[c-'a'];if (node == NULL) {return false;}}return true;}};
