Graph BFS/DFS

by Anton Bagayev

JavaScript

var Queue = function() {
	let queue = [];
	
	this.enqueue = function(elem) {
		queue.push(elem);
	}
	
	this.enqueueCollection = function(array) {
		queue.push(elem);
	}
	
	this.dequeue = function() {
		return queue.shift();
	}
	
	this.view = function(){
		return queue;
	}
}

var Stack = function() {
	let stack = [];
	
	this.push = function(elem) {
		stack.push(elem);
	}
	
	this.pop = function() {
		return stack.pop();
	}
	
	this.view = function(){
		return stack;
	}
}

// testing
/* let q = new Queue();
q.enqueue("a");
q.enqueue("b");
q.enqueue("c");
console.log(q.view());
console.log(q.dequeue());
console.log(q.dequeue());
console.log(q.dequeue());
console.log(q.view());
let s = new Stack();
s.push("a");
s.push("b");
s.push("c");
console.log(s.view());
console.log(s.pop());
console.log(s.pop());
console.log(s.pop());
console.log(s.view()); */

var GraphNode = function(el) {
	let parent = null;
	let children = [];
	let element = el;
	
	this.setParent = function(node){
		parent = node;
	}
	
	this.addChild = function(node) {
		node.setParent(this);
		children.push(node);
	}
	
	this.addChildren = function(array) {
		for(let i = 0; i < array.length; i++) {
			this.addChild(array[i]);
		}
	}
	
	this.hasChildren = function() {
		return (children.length > 0);
	}
	
	this.getChildren = function() {
		return children;
	}
	
	this.getElement = function() {
		return element;
	}
}

var Graph = function(rootNode){
	let root = rootNode;
	
	this.setRoot = function(graphNode) {
		root = graphNode;
	}
	
	this.getRoot = function() {
		return root;
	}
}

// construct graph
// https://medium.com/basecs/deep-dive-through-a-graph-dfs-traversal-8177df5d0f13
let nodeA = new GraphNode("a");
let nodeB = new GraphNode("b");
let nodeC = new GraphNode("c");
let nodeD = new GraphNode("d");
var nodeE = new GraphNode("e");
var nodeF = new GraphNode("f");
var nodeG = new GraphNode("g");
nodeA.addChildren([nodeB, nodeC, nodeG]);
nodeB.addChildren([nodeD,...