From 1395b95b9c7d62edd342bb08020457cd3e07e69e Mon Sep 17 00:00:00 2001 From: Manish Date: Fri, 8 Sep 2023 13:57:19 +1000 Subject: [PATCH] Data Structures: Create a Trie Search Tree --- Data Structures/trie.js | 49 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Data Structures/trie.js diff --git a/Data Structures/trie.js b/Data Structures/trie.js new file mode 100644 index 0000000..7b705b6 --- /dev/null +++ b/Data Structures/trie.js @@ -0,0 +1,49 @@ +// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/create-a-trie-search-tree + +var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2)); +var Node = function () { + this.keys = new Map(); + this.end = false; + this.setEnd = function () { + this.end = true; + }; + this.isEnd = function () { + return this.end; + }; +}; +var Trie = function () { + // Only change code below this line + this.root = new Node(); + this.add = (word) => { + const chars = word.split(""); + let node = this.root; + for (let char of chars) { + if (!node.keys.get(char)) { + node.keys.set(char, new Node()); + } + node = node.keys.get(char); + } + node.setEnd(); + }; + this.isWord = (word) => { + const chars = word.split(""); + let node = this.root; + for (let char of chars) { + node = node.keys.get(char); + if (!node) return false; + } + return node.isEnd(); + }; + this.print = () => { + const words = []; + const recurse = (node, partWord) => { + if (node.isEnd()) words.push(partWord); + for (let [key, childNode] of node.keys.entries()) { + recurse(childNode, partWord + key); + } + }; + recurse(this.root, ""); + return words; + }; + // Only change code above this line +};