Skip to content

Instantly share code, notes, and snippets.

@KodeSeeker
Last active December 14, 2015 22:38
Show Gist options
  • Select an option

  • Save KodeSeeker/5159313 to your computer and use it in GitHub Desktop.

Select an option

Save KodeSeeker/5159313 to your computer and use it in GitHub Desktop.
Given a sorted (increasing order) array, write an algorithm to create a binary tree with minimal height .
public static Node addToTree(int arr[], int start, int end){
if (end < start) {
return null;
}
int mid = (start + end) / 2;
Node n = new TreeNode(arr[mid]);// root
n.left = addToTree(arr, start, mid - 1);//left child
n.right = addToTree(arr, mid + 1, end);//right child
return n;
}
public static Node createMinimalBST(int array[]) {
return addToTree(array, 0, array.length - 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment