Advertisement
stanevplamen

Trie JS

Sep 24th, 2022
898
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.69 KB | Software | 0 0
  1. // JavaScript program to sort an array of strings
  2. // using Trie
  3.  
  4. const MAX_CHAR = 26;
  5.  
  6. class Trie {
  7.  
  8.     // index is set when node is a leaf
  9.     // node, otherwise -1;
  10.     /*to make new trie*/
  11.     constructor()
  12.     {
  13.         this.child = new Array(MAX_CHAR).fill(null);
  14.         this.index = -1;
  15.     }
  16. }
  17.  
  18. /* function to insert in trie */
  19. function insert(root,str,index)
  20. {
  21.     let node = root;
  22.  
  23.     for (let i = 0; i < str.length; i++) {
  24.  
  25.         /* taking ascii value to find index of
  26.         child node */
  27.         let ind = str.charCodeAt(i) - 'a'.charCodeAt(0);
  28.  
  29.         /* making new path if not already */
  30.         if (node.child[ind] == null)
  31.             node.child[ind] = new Trie();
  32.  
  33.         // go to next node
  34.         node = node.child[ind];
  35.     }
  36.  
  37.     // Mark leaf (end of word) and store
  38.     // index of word in arr[]
  39.     node.index = index;
  40. }
  41.  
  42. /* function for preorder traversal */
  43. function preorder(node, arr)
  44. {
  45.     if (node == null)
  46.         return false;
  47.  
  48.     for (let i = 0; i < MAX_CHAR; i++) {
  49.         if (node.child[i] != null) {
  50.  
  51.             /* if leaf node then print key*/
  52.             if (node.child[i].index != -1)
  53.                 document.write(arr[node.child[i].index],"</br>");
  54.  
  55.             preorder(node.child[i], arr);
  56.         }
  57.     }
  58. }
  59.  
  60. function printSorted(arr,n)
  61. {
  62.     let root = new Trie();
  63.  
  64.     // insert all keys of dictionary into trie
  65.     for (let i = 0; i < n; i++)
  66.         insert(root, arr[i], i);
  67.  
  68.     // print keys in lexicographic order
  69.     preorder(root, arr);
  70. }
  71.  
  72. // Driver code
  73.  
  74. let arr = [ "abc", "xy", "bcd" ];
  75. let n = arr.length;
  76. printSorted(arr, n);
  77.  
  78. // This code is contributed by shinjanpatra
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement