How to create a binary search tree with minimal height given a sorted array in JavaScript

Here is one way you can create a binary search tree with minimal height given a sorted array. This assumes that each tree node has a left and right property.

minimalTreeTry in REPL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function minimalTree(array, left = 0, right = array.length - 1) {
if (left > right) return null;
const mid = parseInt((left+right)/2);
const node = new Tree(array[mid]);
node.left = minimalTree(array, left, mid - 1);
node.right = minimalTree(array, mid+1, right);
return node;
}
function Tree(value) {
this.value = value;
this.left = null;
this.right = null;
}

Tests can be found at REPL.it