Skip to content

Commit f77ad9d

Browse files
committed
update: find all words in a trie
1 parent 42e4372 commit f77ad9d

File tree

1 file changed

+41
-0
lines changed
  • src/_DataStructures_/Trees/Trie/all-words-in-trie

1 file changed

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

0 commit comments

Comments
 (0)