Skip to content

Instantly share code, notes, and snippets.

@jmsevold
Created March 22, 2016 03:04
Show Gist options
  • Save jmsevold/59d2a298aa266cf1188c to your computer and use it in GitHub Desktop.
Save jmsevold/59d2a298aa266cf1188c to your computer and use it in GitHub Desktop.
class Node{
constructor(value,children=[]){
this.value = value;
this.children = children;
this.visited = false;
}
}
var node10 = new Node(10);
var node9 = new Node(9);
var node8 = new Node(8, [node9]);
var node7 = new Node(7, [node8, node10]);
var node6 = new Node(6);
var node5 = new Node(5);
var node4 = new Node(4);
var node3 = new Node(3, [node4, node5, node6]);
var node2 = new Node(2, [node3]);
var node1 = new Node(1, [node2, node7]);
/*
1
/ \
2 7
/ / \
3 8 10
/ | \ |
4 5 6 9
*/
var dfs = (node) => {
let stack = [];
stack.push(node);
while (stack.length > 0) {
let node = stack.pop();
if (node.visited === false) {
node.visited = true;
console.log(node.value + " visited");
node.children.forEach((childNode) => {
if (childNode.visited === false) {
stack.push(childNode);
}
});
}
}
};
dfs(node1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment