Skip to content

Instantly share code, notes, and snippets.

@pinkmomo027
Last active June 13, 2018 03:51
Show Gist options
  • Select an option

  • Save pinkmomo027/675a37bee1843a43a8ce605c66ba24f3 to your computer and use it in GitHub Desktop.

Select an option

Save pinkmomo027/675a37bee1843a43a8ce605c66ba24f3 to your computer and use it in GitHub Desktop.
find path to a node
class Node {
constructor(value) {
this.value = value;
this.children = [];
}
add(child) {
this.children.push(child);
}
print(level=0) {
let indent = "";
for (let i = 0; i < level * 2; i++) {
indent += " ";
}
process.stdout.write(`${indent}value : ${this.value} \n`);
if(this.children.length > 0) {
process.stdout.write(`${indent}children ↓↓ \n`);
this.children.forEach(child => {
child.print(level+1);
});
}
}
printPath(value) {
let path = [];
if (this.hasPath(value, path)) {
return path.map(step => step.value).join(" -> ");
} else {
return "No Path Found";
}
}
hasPath(value, opt_path) {
let path = opt_path || [];
function hasPathImpl(node, value, path) {
if (!node) {
return false;
}
path.push(node);
if (node.value == value) {
return true;
}
let bool = false;
for(let i = 0; i < node.children.length; i++) {
bool = bool || hasPathImpl(node.children[i], value, path);
}
if (bool) { return true; }
path.pop();
return false;
}
return hasPathImpl(this, value, path);
}
}
function p(o) {
console.log(o);
}
let root = new Node(0);
let l1 = new Node(10);
let l2 = new Node(100);
let l3 = new Node(500);
root.add(l1);
root.add(l2);
root.add(l3);
let p1 = new Node('A');
let p2 = new Node('B');
l1.add(p1);
l1.add(p2);
let x1 = new Node('X');
l3.add(x1);
let z1 = new Node("horse");
let z2 = new Node("rabbit");
x1.add(z1);
x1.add(z2);
p(root.hasPath(16));
p(root.hasPath('horse'));
p(root.hasPath('rabbit'));
p(root.printPath(16));
p(root.printPath('horse'));
p(root.printPath('rabbit'));
@pinkmomo027
Copy link
Author

pinkmomo027 commented Jun 13, 2018

false
true
true
No Path Found
0 -> 500 -> X -> horse
0 -> 500 -> X -> rabbit
[Finished in 0.1s]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment