Created
February 17, 2014 20:04
-
-
Save jack-wong-build/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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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