Advertisement
Guest User

Untitled

a guest
Jun 20th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. // A trie is special type of tree used commonly for searching strings and matching on stored strings.
  2.  
  3. function TrieNode() {
  4. this.children = {};
  5. this.endOfWord = false;
  6. }
  7.  
  8. function Trie() {
  9. this.root = new TrieNode();
  10. }
  11.  
  12. Trie.prototype.insert = function (word) {
  13. var current = this.root;
  14. for (var i = 0; i < word.length; i++) {
  15.  
  16. var ch = word.charAt(i);
  17. var node = current.children[ch];
  18. if (node == null) {
  19. node = new TrieNode();
  20. current.children[ch] = node;
  21. }
  22. current = node;
  23. }
  24. current.endOfWord = true;
  25. }
  26. Trie.prototype.search = function (word) {
  27. var current = this.root;
  28. for (var i = 0; i < word.length; i++) {
  29. var ch = word.charAt(i);
  30. var node = current.children[ch];
  31. if (node == null) {
  32. return false;
  33. }
  34. current = node;
  35. }
  36. return current.endOfWord;
  37. }
  38.  
  39.  
  40. Trie.prototype.delete = function (word) {
  41. this.deleteRecursively(this.root, word, 0);
  42. }
  43.  
  44. Trie.prototype.deleteRecursively = function (current, word, index) {
  45. if (index == word.length) {
  46. if (!current.endOfWord) {
  47. return false;
  48.  
  49. }
  50. current.endOfWord = false;
  51. return Object.keys(current.children).length == 0;
  52. }
  53. var ch = word.charAt(index),
  54. node = current.children[ch];
  55. if (node == null) {
  56. return false;
  57. }
  58. var shouldDeleteCurrentNode = this.deleteRecursively(node, word, index + 1);
  59. if (shouldDeleteCurrentNode) {
  60. delete current.children[ch];
  61. return Object.keys(current.children).length == 0;
  62. }
  63. return false;
  64. }
  65.  
  66. var tree = new Trie();
  67. tree.insert('sammie');
  68. tree.insert('same');
  69.  
  70.  
  71.  
  72. console.log(tree)
  73.  
  74. // tree.delete("same");
  75.  
  76. var r = tree.search('same');
  77.  
  78. console.log(r)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement