26叉树? Trie(发音类似 “try”)或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。

优点:利用公共前缀减少查询时间,最大限度减少无谓字符串比较,查询效率比哈希树高。

图片理解

image.png
image.png

  1. var Trie = function () {
  2. this.root = {}
  3. };
  4. /**
  5. * @param {string} word
  6. * @return {void}
  7. */
  8. Trie.prototype.insert = function (word) {
  9. let cur = this.root
  10. for (let c of word) {
  11. if (!cur[c]) {
  12. cur[c] = {}
  13. }
  14. cur = cur[c]
  15. }
  16. cur.isEnd = true
  17. };
  18. /**
  19. 查找前缀的公共方法
  20. */
  21. Trie.prototype.searchPrefix = function(prefix) {
  22. let cur = this.root
  23. for (let c of prefix) {
  24. if (!cur[c]) {
  25. return false
  26. }
  27. cur = cur[c]
  28. }
  29. return cur
  30. }
  31. /**
  32. * @param {string} word
  33. * @return {boolean}
  34. * return这句,如果不是End节点,不为false 而是 undefine
  35. */
  36. Trie.prototype.search = function (word) {
  37. const node = this.searchPrefix(word)
  38. return node != undefined && node.isEnd != undefined
  39. };
  40. /**
  41. * @param {string} prefix
  42. * @return {boolean}
  43. */
  44. Trie.prototype.startsWith = function (prefix) {
  45. return this.searchPrefix(prefix)
  46. };
  47. /**
  48. * Your Trie object will be instantiated and called as such:
  49. * var obj = new Trie()
  50. * obj.insert(word)
  51. * var param_2 = obj.search(word)
  52. * var param_3 = obj.startsWith(prefix)
  53. */

参考文献:

  1. CSDN