You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
My solution for EXERCISE 1 − IMPLEMENTING A TRIE (Chapter 7 in the pdf). After reviewing the author's solution, I've learned to use the insert function itself recursively. Here's my original function where a recursive function inside "insert" method is used:
classTrieNode{constructor(){this.children={};this.isEndOfWord=false;}}classTrie{constructor(){this.root=newTrieNode();}/** * * @param {string} word */insert(word){leti=0;/** * * @param {TrieNode} currentNode * @param {string} currentWord */constcheckFx=(currentNode,currentChar)=>{//for new charif(!Object.keys(currentNode.children).includes(currentChar)){consttrieNode=newTrieNode();i++;currentNode.children={
...currentNode.children,[currentChar]: trieNode,};if(i===word.length){trieNode.isEndOfWord=true;returnconsole.log("end of word reached: ",currentChar);}returncheckFx(trieNode,word[I]);}else{//instead of current node, move on to the child node//e.g., e of eaten already exists in root node's children objconstchildNode=currentNode.children[currentChar];//increment to next chari++;returncheckFx(childNode,word[i]);}};checkFx(this.root,word[i]);}}//testconsttrie=newTrie();trie.insert("cat");trie.insert("car");trie.insert("cup");trie.insert("eat");trie.insert("eaten");//log the entire trie objectconsole.log(JSON.stringify(trie,null,2));
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
My solution for EXERCISE 1 − IMPLEMENTING A TRIE (Chapter 7 in the pdf). After reviewing the author's solution, I've learned to use the insert function itself recursively. Here's my original function where a recursive function inside "insert" method is used:
Beta Was this translation helpful? Give feedback.
All reactions