Skip to content

Instantly share code, notes, and snippets.

@IAMIronmanSam
Last active January 17, 2019 04:11
Show Gist options
  • Save IAMIronmanSam/7df999a6050dab3c6a399944eecdb2fd to your computer and use it in GitHub Desktop.
Save IAMIronmanSam/7df999a6050dab3c6a399944eecdb2fd to your computer and use it in GitHub Desktop.
function Node(data) {
this.data = data;
this.parent = null;
this.children = [];
}
function Tree(data) {
var node = new Node(data);
this._root = node;
}
function Queue() {
this.dataStore = []
this.enqueue = function enqueue(element) {
this.dataStore.push(element)
}
this.dequeue = function dequeue() {
return this.dataStore.shift()
}
this.front = function front() {
return this.dataStore[0]
}
this.back = function back() {
return this.dataStore[this.dataStore.length - 1]
}
}
Tree.prototype.add = function(data, toData, traversal) {
var child = new Node(data)
, parent = null
, callback = function(node) {
if (node.data === toData) {
parent = node;
}
};
this.contains(callback, traversal);
if (parent) {
parent.children.push(child);
child.parent = parent;
} else {
throw new Error('Cannot add node to a non-existent parent.');
}
};
Tree.prototype.traverseBF = function(callback) {
var queue = new Queue();
queue.enqueue(this._root);
currentTree = queue.dequeue();
while(currentTree){
for (var i = 0, length = currentTree.children.length; i < length; i++) {
queue.enqueue(currentTree.children[i]);
}
callback(currentTree);
currentTree = queue.dequeue();
}
};
Tree.prototype.contains = function(callback, traversal) {
traversal.call(this, callback);
};
var tree = new Tree('CEO');
tree.add('Bill Gates', 'CEO', tree.traverseBF);
console.log(tree);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment