Data Structures: Create a Trie Search Tree
This commit is contained in:
parent
d5dd37d94c
commit
1395b95b9c
49
Data Structures/trie.js
Normal file
49
Data Structures/trie.js
Normal file
@ -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
|
||||
};
|
Loading…
Reference in New Issue
Block a user