A coding challenge to construct a binary tree from an array.
class BinaryTreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
function makeBst(arr){
if(!arr || arr.length <= 1){
return arr;
}
let top = arr[Math.floor(arr.length / 2)];
let node = new BinaryTreeNode(top);
let rightArr = arr.splice(Math.floor(arr.length /2), arr.length);
let leftArr = arr.splice(0, Math.floor(arr.length / 2));
node.right = makeBst(rightArr);
node.left = makeBst(leftArr);
return node;
}
const arr = [1, 2, 3, 4, 5, 6, 7];
makeBst(arr);
The function returns the correct output, and all known edge cases have been accounted for. I would like feedback on cleaning up the conditional logic, as well as help determining the time and space complexity (and the possibility of improving both).