|
| 1 | +const Trie = require('../index'); |
| 2 | + |
| 3 | +function getAllUniqueWords(root, level, word) { |
| 4 | + let result = []; |
| 5 | + |
| 6 | + if (!root) return result; |
| 7 | + |
| 8 | + if (root.isEndOfWord) { |
| 9 | + let temp = ''; |
| 10 | + for (let i = 0; i < level; i += 1) { |
| 11 | + temp += String(word[i]); |
| 12 | + } |
| 13 | + result = [...result, temp]; |
| 14 | + } |
| 15 | + |
| 16 | + for (let i = 0; i < 26; i += 1) { |
| 17 | + if (root.children[i]) { |
| 18 | + // eslint-disable-next-line no-param-reassign |
| 19 | + word[level] = String.fromCharCode(i + 'a'.charCodeAt(0)); |
| 20 | + result = [...result, ...getAllUniqueWords(root.children[i], level + 1, word)]; |
| 21 | + } |
| 22 | + } |
| 23 | + return result; |
| 24 | +} |
| 25 | + |
| 26 | +function allUniqueWordsFromTrie(root) { |
| 27 | + const word = []; // char arr to store a word |
| 28 | + for (let i = 0; i < 26; i += 1) { |
| 29 | + word[i] = null; |
| 30 | + } |
| 31 | + return getAllUniqueWords(root, 0, word); |
| 32 | +} |
| 33 | + |
| 34 | +// const words = ['bed', 'ball', 'apple', 'java', 'javascript', 'bed']; |
| 35 | +// const trie = new Trie(); |
| 36 | + |
| 37 | +// words.forEach(word => trie.insert(word)); |
| 38 | +// console.log(allUniqueWordsFromTrie(trie.root)); |
| 39 | + |
| 40 | +module.exports = allUniqueWordsFromTrie; |
0 commit comments