Skip to content

Instantly share code, notes, and snippets.

@DaniloShan
Created September 14, 2017 08:07
Show Gist options
  • Save DaniloShan/3e387029aed64c5e6771f3274fb93109 to your computer and use it in GitHub Desktop.
Save DaniloShan/3e387029aed64c5e6771f3274fb93109 to your computer and use it in GitHub Desktop.
trie tree
class TreeNode {
constructor(key, isLeaf = false) {
this.key = key;
this.isLeaf = isLeaf;
this.children = new Map();
}
append(node) {
let curNode = this.children.get(node.key);
if (!this.exist(node.key)) {
this.children.set(node.key, node);
curNode = node;
} else {
curNode.isLeaf = node.isLeaf || curNode.isLeaf;
}
return curNode;
}
getChildren() {
return Array.from(this.children.values());
}
find(key) {
return this.children.get(key);
}
exist(key) {
return key === '.' || this.children.has(key);
}
}
class TrieTree {
constructor() {
this.root = new TreeNode('root');
}
append(char) {
let preventNode = this.root;
char.split('').forEach((c, index) => {
let node = new TreeNode(c);
if (index === char.length - 1) {
node.isLeaf = true;
}
preventNode = preventNode.append(node);
});
return this.root;
}
find(char, root = this.root) {
let curNode = root;
for (let i = 0, il = char.length; i < il; i++) {
if (i === char.length - 1) {
return char[i] === '.' ?
curNode.getChildren().some(item => item.isLeaf)
:
curNode.exist(char[i]) && curNode.find(char[i]).isLeaf;
}
if (char[i] === '.') {
return curNode.getChildren()
.some((item) => this.find(char.slice(i + 1, char.length), item));
}
curNode = curNode.find(char[i]);
if (!curNode) {
return false;
}
}
}
}
const tree = new TrieTree();
tree.append('ceb');
tree.append('bcd');
tree.append('bef');
tree.append('ae');
console.log(tree.find('.ef'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment