Skip to content

Instantly share code, notes, and snippets.

@woonketwong
Created February 17, 2014 20:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save woonketwong/9058021 to your computer and use it in GitHub Desktop.
Save woonketwong/9058021 to your computer and use it in GitHub Desktop.
Given a sorted array, write an algorithm to create a binary search tree with minimal height.
function createMinimalBST(array, start, end){
if (end < start){
return null;
}
var mid = Math.floor( (start + end) / 2 );
var node = {val: array[mid], left: null, right: null};
node.left = createMinimalBST(array, start, mid-1);
node.right = createMinimalBST(array, mid+1, end);
return node;
}
// array1 = [1,2,3,4,5,6,7,8,9];
// var result = createMinimalBST(array1, 0, array1.length-1);
// console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment