Skip to content

Instantly share code, notes, and snippets.

@JoyceeLee
Created July 12, 2014 23:44
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 JoyceeLee/627488dd7113966bfd92 to your computer and use it in GitHub Desktop.
Save JoyceeLee/627488dd7113966bfd92 to your computer and use it in GitHub Desktop.
/*4.3 Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree
with minimal height.*/
public class Solution {
public TreeNode arrayToBST(int[] A) {
return buildTree(A, 0, A.length);
}
public TreeNode buildTree(int[] A, int s, int e) {
if(s>=e) return null;
int mid = (s+e) >> 1;
TreeNode root = new TreeNode(A[mid]);
root.left = buildTree(A, s, mid);
root.right = buildTree(A, mid+1, e);
return root;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment