function Tree(data) {
this.data = data;
this.children = [];
}
Tree.prototype.addChild = function(data) {
const child = new Tree(data);
this.children.push(child);
};
Tree.prototype.contains = function(target) {
if (this.data === target) {
return true;
}
for (let i = 0; i < this.children.length; i++) {
const child = this.children[i];
if (child.contains(target)) {
return true;
}
}
return false;
};
function inOrderTraversal(tree, callback = identity, array = []) {
if (tree) {
inOrderTraversal(tree.left, callback, array);
visit(array, tree.data);
inOrderTraversal(tree.right, callback,array);
}
return array.map(callback);
}
function preOrderTraversal(tree, callback = identity, array = []) {
if (tree) {
visit(array, tree.data);
preOrderTraversal(tree.left, callback, array);
preOrderTraversal(tree.right, callback, array);
}
return array.map(callback);
}
function postOrderTraversal(tree, callback = identity, array = []) {
if (tree) {
postOrderTraversal(tree.left, callback, array);
postOrderTraversal(tree.right, callback, array);
visit(array, tree.data);
}
return array.map(callback);
}
function visit(array, data) {
array.push(data);
}
function identity(element) {
return element
}
function BinaryTree(data) {
this.data = data;
this.left = null;
this.right = null;
}
BinaryTree.prototype.addChild = function(data) {
const child = new BinaryTree(data);
if (!this.left) {
this.left = child;
} else if (!this.right) {
this.right = child;
} else {
}
}
BinaryTree.prototype.contains = function(target, containsTarget = false) {
if (this.data === target) {
return true;
}
if (this.left && this.left.contains(target, containsTarget)) {
containsTarget = true;
} else if (this.right && this.right.contains(target, containsTarget)) {
containsTarget = true;
}
return containsTarget;
};