const ALPHABET_SIZE = 26;
class TrieNode {
constructor() {
this
.children = Array(ALPHABET_SIZE).fill(
null
);
this
.isLeaf =
false
;
this
.word = [];
}
}
function
getNewTrieNode() {
const pNode =
new
TrieNode();
return
pNode;
}
function
insert(root, word) {
let pCrawl = root;
for
(let level = 0; level < word.length; level++) {
if
(!word[level].match(/[A-Z]/)) {
continue
;
}
const index = word.charCodeAt(level) - 'A
'.charCodeAt(0);
// If there is no node for this character, create a new one
if (!pCrawl.children[index]) {
pCrawl.children[index] = getNewTrieNode();
}
// Move the pointer to the child node
pCrawl = pCrawl.children[index];
}
// Mark the node as end of word
pCrawl.isLeaf = true;
// Store the word at this node
pCrawl.word.push(word);
}
// Function to print all the words stored at a TrieNode
function printAllWords(root) {
// If the node is end of word, print all the words stored at this node
if (root.isLeaf) {
root.word.forEach((str) => {
console.log(str);
});
}
// Traverse through all the children nodes
for (let i = 0; i < ALPHABET_SIZE; i++) {
const child = root.children[i];
// If there is a child node, call printAllWords for this node
if (child) {
printAllWords(child);
}
}
}
// Function to search for a pattern in Trie
function search(root, pattern) {
let pCrawl = root;
// Traverse through each character of the pattern
for (let level = 0; level < pattern.length; level++) {
// Get the index of the character
const index = pattern.charCodeAt(level) - '
A'.charCodeAt(0);
if
(!pCrawl.children[index]) {
return
false
;
}
pCrawl = pCrawl.children[index];
}
printAllWords(pCrawl);
return
true
;
}
function
findAllWords(dict, pattern) {
const root = getNewTrieNode();
dict.forEach((word) => {
insert(root, word);
});
if
(!search(root, pattern)) {
console.log(
"No match found"
);
}
}
const dict = [
"Hi"
,
"Hello"
,
"HelloWorld"
,
"HiTech"
,
"HiGeek"
,
"HiTechWorld"
,
"HiTechCity"
,
"HiTechLab"
];
const pattern =
"HT"
;
findAllWords(dict, pattern);