I'm reviewing bfs and dfs concepts and recently wrote this search method for a Trie tree. I believe it is bfs because we're searching each level starting from the root if the next value exists. I'm not sure what implementing dfs would look like in a problem like this. I could be completely wrong though.
class TrieTree {
constructor() {
this.root = new TreeNode();
}
insert(word) {
let currentNode = this.root;
for (let char of word) {
if (currentNode.children.has(char)) {
currentNode = currentNode.children.get(char);
continue;
} else {
currentNode.children.set(char, new TreeNode(char));
currentNode = currentNode.children.get(char);
}
}
currentNode.isWord = true;
}
//I'm not sure if this should be called bfs or dfs
bfs(searchTerm) {
let currentNode = this.root;
for (let char of searchTerm) {
if (currentNode.children.has(char)) {
currentNode = currentNode.children.get(char);
} else {
return false;
}
}
return (currentNode.isWord)
}
}
class TreeNode {
constructor(val) {
this.data = val;
this.children = new Map(); //collection of nodes in TS we would use TreeNode[];
this.isWord = false;
}
}
let tree = new TrieTree();
tree.insert("hello");
tree.insert("bucky");
tree.insert("hell");
console.log(tree.bfs("bucky"));