Skip to content

Instantly share code, notes, and snippets.

@Trshant
Created March 8, 2019 01:31
Show Gist options
  • Save Trshant/08ee22f00f44d2ed019f4f4bf62301aa to your computer and use it in GitHub Desktop.
Save Trshant/08ee22f00f44d2ed019f4f4bf62301aa to your computer and use it in GitHub Desktop.
implementation of a prefix tree
var mother_node = new node(null, null);
var string_to_store = "rupsa";
var previous_node = mother_node;
var stored_nodes = [];
string_to_store.split('').forEach(function (element, index) {
var newNode = new node(element, previous_node);
stored_nodes.push(newNode);
previous_node = newNode;
})
console.log(stored_nodes);
var trie = new prefix_tree(null);
trie.addToTree("to");
trie.addToTree("tea");
console.log(trie.stored_nodes);
reply = trie.searchInTree("toe");
console.log(reply);
reply = trie.searchInTree("to");
console.log(reply);
type NameOrNameArray = number[] | string[];
class node {
value: number | string | null;
childNodes: NameOrNameArray;
constructor(value, parentNode) {
this.value = value;
this.childNodes = [];
if (parentNode != null) {
parentNode.addChild(this);
}
}
addChild(childNode) {
this.childNodes.push(childNode);
}
searchChildNodes(valueToSearch) {
var element: any;
for ( element of this.childNodes) {
if (element.value == valueToSearch) {
return element;
}
}
return null;
}
}
class prefix_tree {
mother_node: any;
previous_node: any;
stored_nodes: any[];
constructor(value) {
this.mother_node = new node(null, null);
this.previous_node = this.mother_node;
this.stored_nodes = [];
//console.log(this.previous_node, this.mother_node);
}
addToTree(StringOrNumber) {
this.previous_node = this.mother_node;
for (var element of StringOrNumber.split('')) {
//console.log(element, this.previous_node ) ;
var oldNode = this.previous_node.searchChildNodes(element);
if (oldNode == null) {
var newNode = new node(element, this.previous_node);
this.stored_nodes.push(newNode);
this.previous_node = newNode;
} else {
this.previous_node = oldNode;
}
}
var newNode = new node(null, this.previous_node);
this.stored_nodes.push(newNode);
}
searchInTree(StringOrNumber) {
this.previous_node = this.mother_node;
for (var element of StringOrNumber.split('')) {
var oldNode = this.previous_node.searchChildNodes(element);
if (oldNode == null) {
return false;
} else {
this.previous_node = oldNode;
}
}
var oldNode = this.previous_node.searchChildNodes(null);
if (oldNode == null) {
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment