题目
题目来源:力扣(LeetCode)
Trie(发音类似 “try”)或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。
请你实现 Trie 类:
Trie() 初始化前缀树对象。
void insert(String word) 向前缀树中插入字符串 word 。
boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。
boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。
 
示例:
输入
[“Trie”, “insert”, “search”, “search”, “startsWith”, “insert”, “search”]
[[], [“apple”], [“apple”], [“app”], [“app”], [“app”], [“app”]]
输出
[null, null, true, false, true, null, true]
解释
Trie trie = new Trie();
trie.insert(“apple”);
trie.search(“apple”);   // 返回 True
trie.search(“app”);     // 返回 False
trie.startsWith(“app”); // 返回 True
trie.insert(“app”);
trie.search(“app”);     // 返回 True
思路分析
Trie树,又叫字典树、前缀树(Prefix Tree)、单词查找树 或 键树,是一种多叉树结构。
Trie树的3个基本性质:
- 根节点不包含字符,除根节点外的每一个子节点都包含一个字符。
 - 从根节点到某一个节点,路径上经过的字符连接起来,为该节点对应的字符串。
 - 每个节点的所有子节点包含的字符互不相同。
 
var Trie = function () {// 初始化根节点// 根节点不保存任何信息this.children = {};};/*** @param {string} word* @return {void}*/Trie.prototype.insert = function (word) {// 从字典树的根开始,插入字符串let node = this.children;for (const ch of word) {// 子节点不存在,创建一个新的子节点if (!node[ch]) {node[ch] = {};}// 子节点存在,沿着指针移动到子节点,继续处理下一个字符node = node[ch];}// 布尔字段 isEnd,表示该节点是否为字符串的结尾node.isEnd = true;};/*** @param {string} prefix* @return {void}*/Trie.prototype.searchPrefix = function (prefix) {// 从字典树的根开始,查找前缀let node = this.children;for (const ch of prefix) {// 子节点不存在,说明字典树中不包含该前缀,返回空指针if (!node[ch]) {return false;}// 子节点存在,沿着指针移动到子节点,继续搜索下一个字符node = node[ch];}return node;}/*** @param {string} word* @return {boolean}*/Trie.prototype.search = function (word) {const node = this.searchPrefix(word);// 若搜索到了前缀的末尾,就说明字典树中存在该前缀。// 此外,若前缀末尾对应节点的 isEnd 为真,则说明字典树中存在该字符串return node !== undefined && node.isEnd !== undefined;};/*** @param {string} prefix* @return {boolean}*/Trie.prototype.startsWith = function (prefix) {return this.searchPrefix(prefix);};/*** Your Trie object will be instantiated and called as such:* var obj = new Trie()* obj.insert(word)* var param_2 = obj.search(word)* var param_3 = obj.startsWith(prefix)*/
参考资料:
https://leetcode-cn.com/problems/implement-trie-prefix-tree/solution/shi-xian-trie-qian-zhui-shu-by-leetcode-ti500/
https://leetcode-cn.com/problems/implement-trie-prefix-tree/solution/fu-xue-ming-zhu-cong-er-cha-shu-shuo-qi-628gs/
https://blog.csdn.net/weixin_39778570/article/details/81990417
