let node = function(data) {
this.data = data;
this.left = null;
this.right = null;
}
let bst = function() {
this.root = null;
}
bst.prototype.sortedArrToBST = function(arr, start, end) {
// base
if (start > end) return null;
// get middle element and make it root
let mid = Math.floor((start + end) / 2);
let nd = new node(arr[mid]);
// recursively construct left subtree and make it left child
nd.left = this.sortedArrToBST(arr, start, mid - 1);
// recursively construct right subtree and make it right child
nd.right = this.sortedArrToBST(arr, mid + 1, end);
return nd;
}
bst.prototype.preOrder = function(node) {
if (!node) return null;
console.log(node.data);
this.preOrder(node.left);
this.preOrder(node.right);
}
let tree = new bst();
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const n = arr.length;
let root = tree.sortedArrToBST(arr, 0, n - 1);
console.log('preOrder');
tree.preOrder(root);