Binary Search Tree
by LyndseyB
Babel + JSX
const createNode = function(value) {
return {
value,
left: null,
right: null
};
};
const insertNode = function(root, value) {
const node = createNode(value);
if(value > root.value) {
root.right = node;
} else {
root.left = node;
}
return root;
};
const createTree = function(input) {
let root = null;
input.forEach((value, index) => {
const node = createNode(value);
if(!root) {
root = node;
} else {
insertNode(root, value);
}
});
return root;
};
const binarySearchTree = function(input, callback) {
if (!Array.isArray(input)) {
return callback('Input should be an array of integers');
}
// filter out non-integer types
const filtered = input.filter(i => typeof(i) === 'number');
if (filtered.length === 0) {
return callback('Input should contain an array with at least one integer');
}
const tree = createTree(filtered);
// return methods
return callback(null, {
tree,
});
};
const bTreeInput = [8, 3, 10, 14, 13, 6, 1, 4, 7];
binarySearchTree(bTreeInput, (err, result) => {
if(err) {
throw(err);
}
console.log(result.tree);
});