Skip to content

Instantly share code, notes, and snippets.

@puttputt
Created October 12, 2017 21:36
Show Gist options
  • Save puttputt/0e373b4bfa56a8a9a89fa8a7d7fe66bc to your computer and use it in GitHub Desktop.
Save puttputt/0e373b4bfa56a8a9a89fa8a7d7fe66bc to your computer and use it in GitHub Desktop.
String Tree Search
export class TreeNode {
label : any;
data : any;
nodes : TreeNode[];
constructor(label : any) {
this.label = label;
this.nodes = [];
}
}
export class StringTree {
rootNode : TreeNode = new TreeNode('');
public find(word : string) : string[] {
let chars = Array.from(word);
let node = this.findNode(chars, this.rootNode);
return this.listData(node, []);
}
private findNode(chars: string[], node : TreeNode) : TreeNode {
let item = chars.shift();
if(item == undefined) {
return node;
} else {
var nextNode = node.nodes.find((node) => {
return node.label == item
});
if(nextNode) {
return this.findNode(chars, nextNode);
}
return node;
}
}
private listData(node : TreeNode, result: any[]) : any[] {
if(node.nodes.length == 0) {
if(node.data) {
result.push(node.data);
}
return result;
} else {
node.nodes.forEach(element => {
return this.listData(element, result);
});
return result;
}
}
public insert(fullWord : string) {
let word = Array.from(fullWord);
this.insertAndBuild(word, this.rootNode, fullWord);
}
private insertAndBuild(chars : string[], node : TreeNode, fullWord : string) {
let item = chars.shift();
if(item == undefined) {
node.data = fullWord;
return;
} else {
var exists = false;
let foundNode = node.nodes.find(n => {
return n.label == item;
})
if(foundNode) {
this.insertAndBuild(chars, foundNode, fullWord);
} else {
let newNode = new TreeNode(item);
node.nodes.push(newNode);
this.insertAndBuild(chars, newNode, fullWord);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment