<script>
function char_int(c) {
return c.charCodeAt(0) - "a".charCodeAt(0);
}
function int_to_char(c) {
return String.fromCharCode(c + "a".charCodeAt(0));
}
const SIZE = 26;
class TrieNode {
constructor() {
this.Child = new Array(SIZE);
this.leaf = false;
}
}
function getNode() {
const newNode = new TrieNode();
newNode.leaf = false;
for (let i = 0; i < SIZE; i++) {
newNode.Child[i] = null;
}
return newNode;
}
function insert(root, Key) {
const n = Key.length;
let pChild = root;
for (let i = 0; i < n; i++) {
const index = char_int(Key[i]);
if (pChild.Child[index] == null) {
pChild.Child[index] = getNode();
}
pChild = pChild.Child[index];
}
pChild.leaf = true;
}
function searchWord(root, Hash, str) {
if (root.leaf == true) {
document.write(str+"<br>");
}
for (let K = 0; K < SIZE; K++) {
if (Hash[K] == true && root.Child[K] != null) {
const c = int_to_char(K);
searchWord(root.Child[K], Hash, str + c);
}
}
}
function PrintAllWords(Arr, root, n) {
const Hash = new Array(SIZE).fill(false);
for (let i = 0; i < n; i++) {
Hash[char_int(Arr[i])] = true;
}
let pChild = root;
let str = "";
for (let i = 0; i < SIZE; i++) {
if (Hash[i] == true && pChild.Child[i]) {
str += int_to_char(i);
searchWord(pChild.Child[i], Hash, str);
str = "";
}
}
}
const Dict = ["go", "bat", "me", "eat", "goal", "boy", "run"];
const root = getNode();
const n = Dict.length;
for (let i = 0; i < n; i++) {
insert(root, Dict[i]);
}
const arr = ["e", "o", "b", "a", "m", "g", "l"];
const N = arr.length;
PrintAllWords(arr, root, N);
</script>