Skip to content

Commit

Permalink
Complete tree/tree.js
Browse files Browse the repository at this point in the history
  • Loading branch information
fay-jai committed Dec 24, 2014
1 parent 0e5c3a1 commit eacfd89
Showing 1 changed file with 39 additions and 3 deletions.
42 changes: 39 additions & 3 deletions tree/tree.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,61 @@ Your tree should have methods named "addChild" and "contains".

var treeMaker = function () {
//tree code goes here!

var tree = Object.create(treeMaker.methods);
tree.root = null;
return tree;
};

var makeNode = function (value) {

return {
value : value,
children : []
};
};

//methods go here!

treeMaker.methods = {};

treeMaker.methods.addChild = function (value) {
var newNode = makeNode(value);

// check if tree has root yet
if (this.isEmpty()) {
this.root = newNode;
} else {
this.root.children.push(newNode);
}
};

treeMaker.methods.contains = function (value, node) {
if (this.isEmpty()) {
return false;
}

var result;
// initialize node
if (node === void 0) {
node = this.root;
}

if (node.value === value) {
result = true;
} else if (node.children.length === 0) {
result = false;
} else {
// iterate through all children
for (var i = 0; i < node.children.length; i += 1) {
if (this.contains(value, node.children[i])) {
result = true;
break;
}
}
}

return result;
};

treeMaker.methods.isEmpty = function () {

return this.root === null;
};

0 comments on commit eacfd89

Please sign in to comment.