树和二叉搜索树

树 Tree
tree.png

二叉搜索树

二叉搜索树任何一个结点,它的左子树的所有结点都要小于这个根结点,它的右子树的所有结点都要大于根结点。

二叉树搜索树中序遍历是一个升序的序列。

二叉搜索树查找的效率更高。

binary_search_tree.png

Trie 树

基本结构

字典树,即 Trie 树,又称单词查找树或键树,是一种树形结构。
典型应用是用于统计和排序大量的字符串(不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。

Trie 树不是一颗二叉树,是多叉树。

优点:最大限度地减少无谓的字符串比较,查找效率比哈希表高。

trie.webp

基本性质

  • 结点本身不存完整单词;
  • 从根结点到某一结点,路径上经过的字符连接起来,为该结点对应的字符串;
  • 每个结点的所有子结点路径代表的字符都不相同。

核心思想

Trie 树的核心思想就是空间换时间。

利用字符串的公共前缀来降低查询时间的开销以达到提高效率的目的。

字典树结构

trie_struct.png

相关题目

二叉树的层次遍历

实现 Trie (前缀树)(亚马逊、微软、谷歌在半年内面试中考过)

单词搜索 II (亚马逊、微软、苹果在半年内面试中考过)

  1. // 二叉树的层次遍历
  2. /**
  3. * 广度优先搜索
  4. * @param {TreeNode} root
  5. * @return {number[][]}
  6. */
  7. var levelOrder = function(root) {
  8. if (!root) return [];
  9. const ans = [];
  10. const queue = [root];
  11. while (queue.length) {
  12. let len = queue.length;
  13. ans.push([]);
  14. while (len--) {
  15. const n = queue.shift();
  16. ans[ans.length - 1].push(n.val);
  17. n.left && queue.push(n.left);
  18. n.right && queue.push(n.right);
  19. }
  20. }
  21. return ans;
  22. };
  1. // 实现 Trie (前缀树)
  2. var Trie = function() {
  3. this.children = {};
  4. };
  5. /**
  6. * @param {string} word
  7. * @return {void}
  8. */
  9. Trie.prototype.insert = function(word) {
  10. let nodes = this.children;
  11. for (const ch of word) {
  12. if (!nodes[ch]) {
  13. nodes[ch] = {};
  14. }
  15. nodes = nodes[ch];
  16. }
  17. nodes.isEnd = true;
  18. };
  19. Trie.prototype.searchPrefix = function(word) {
  20. let nodes = this.children;
  21. for (const ch of word) {
  22. if (!nodes[ch]) {
  23. return false;
  24. }
  25. nodes = nodes[ch];
  26. }
  27. return nodes;
  28. };
  29. /**
  30. * @param {string} word
  31. * @return {boolean}
  32. */
  33. Trie.prototype.search = function(word) {
  34. const nodes = this.searchPrefix(word);
  35. return nodes != undefined && nodes.isEnd !== undefined;
  36. };
  37. /**
  38. * @param {string} prefix
  39. * @return {boolean}
  40. */
  41. Trie.prototype.startsWith = function(prefix) {
  42. return this.searchPrefix(prefix);
  43. };
  44. /**
  45. * Your Trie object will be instantiated and called as such:
  46. * var obj = new Trie()
  47. * obj.insert(word)
  48. * var param_2 = obj.search(word)
  49. * var param_3 = obj.startsWith(prefix)
  50. */