做者:Hussain Mir Ali翻译:疯狂的技术宅javascript
原文:https://www.softnami.com/post...html
未经容许严禁转载前端
对于搜索字符串的需求,在最坏的状况下,二叉搜索树的时间复杂度可能为 O(n),“n” 是二叉树中存储的字符串的总数量。因此为了在最佳时间内搜索字符串,须要一种性能更好的数据结构。 Trie 树(又名单词搜索树)能够避免在搜索字符串时遍历整个树。仅包含字母的字符串会把 trie 节点的子级数量限制为 26。这样搜索字符串的时间复杂度为 O(s),其中 “s” 为字符串的长度。与二进制搜索树相比,trie 树在搜索字符串方面效率更高。java
trie 树中单个节点的结构由长度为 26 的数组和一个布尔值组成,这个布尔值用来标识其是否为叶子节点。此外,叶子节点能够具备整数值或映射到字符串的其余类型的值。数组中的每一个索引表明从 a 到 z 的字母,而且每一个索引能够有一个 TrieNode
实例。node
上图表示 trie 树中的根节点。程序员
该实现包含两个类,一个用于 trie 节点,另外一个用于 trie 树。实现的语言是带有 ES6 规范的 JavaScript。面试
TrieNode
类的属性为value
,isEnd
和 arr
。变量 arr
是长度为 26 的数组,其中填充了 null
值。segmentfault
class TrieNode { constructor() { this.value = undefined; this.isEnd = false; this.arr = new Array(26).fill(null); } }
TrieTree
类具备 insert
、searchNode
、startsWith
、printString
和 getRoot
方法。能够用 startsWith
方法执行前缀搜索。insert
方法将字符串和值做为参数。数组
class TrieTree { constructor() { this.root = new TrieNode(); } insert(word, value) { let node = this.root; for (let i = 0; i < word.length; i++) { const index = parseInt(word[i], 36) - 10; if (node.arr[index] === null) { const temp = new TrieNode(); node.arr[index] = temp; node = temp; } else { node = node.arr[index]; } } node.isEnd = true; node.value = value; } getRoot() { return this.root; } startsWith(prefix) { const node = this.searchNode(prefix); if (node == null) { return false; } else { this.printStrings(node, ""); return true; } } printStrings(node, prefix) { if (node.isEnd) console.log(prefix); for (let i = 0; i < node.arr.length; i++) { if (node.arr[i] !== null) { const character = String.fromCharCode('a'.charCodeAt() + i); this.printStrings(node.arr[i], prefix + "" + (character)); } } } searchNode(str) { let node = this.root; for (let i = 0; i < str.length; i++) { const index = parseInt(str[i], 36) - 10; if (node.arr[index] !== null) { node = node.arr[index]; } else { return null; } } if (node === this.root) return null; return node; } }
下面的代码显示了如何实例化 “TrieTree” 类,还演示了各类方法的用法。服务器
const trieTree = new TrieTree(); trieTree.insert("asdfasdf", 5); trieTree.insert("cdfasdfas", 23); trieTree.insert("cdfzsvljsdf", 42); let answer = trieTree.searchNode("asdfasdf"); console.log(answer.value); //5 answer = trieTree.startsWith("cdf"); console.log(answer); //asdfas //zsvljsdf //true
不一样方法的时间和空间复杂度以下:
在前端开发中,trie 树可用于如下程序:
此外 trie 树能够用来存储电话号码、IP地址和对象等。