Created
October 31, 2021 07:15
-
-
Save ahamed/4e569d00ade1ff19408bc8adbd489d6c to your computer and use it in GitHub Desktop.
Implement the Trie data structure for storing worlds in an efficient way.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function Node(character) { | |
| this.value = character; | |
| this.endOfWord = false; | |
| this.children = {}; | |
| } | |
| class Trie { | |
| constructor() { | |
| this.root = new Node(null); | |
| } | |
| insert(word) { | |
| let current = this.root; | |
| for (let char of word) { | |
| if (current.children[char] === undefined) { | |
| current.children[char] = new Node(char); | |
| } | |
| current = current.children[char]; | |
| } | |
| current.endOfWord = true; | |
| } | |
| search(word) { | |
| let current = this.root; | |
| for (let char of word) { | |
| if (current.children[char] === undefined) { | |
| return false; | |
| } | |
| current = current.children[char]; | |
| } | |
| return current.endOfWord; | |
| } | |
| } | |
| const trie = new Trie(); | |
| trie.insert('hello'); | |
| trie.insert('world'); | |
| console.log(trie.search('world')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment